C# ASP.NET MVC-未通过控制器查看的对象
我认为:C# ASP.NET MVC-未通过控制器查看的对象,c#,asp.net-mvc,C#,Asp.net Mvc,我认为: @{ var categories = (List<C_Category>)Model.c; } @foreach (C_Category cat in categories) { <option value="@cat.C_Id">@cat.C_Name</option> } 在我的控制器中: [HttpGet] public ActionResult Admin() { using (var
@{
var categories = (List<C_Category>)Model.c;
}
@foreach (C_Category cat in categories)
{
<option value="@cat.C_Id">@cat.C_Name</option>
}
在我的控制器中:
[HttpGet]
public ActionResult Admin()
{
using (var context = new sopingadbEntities())
{
List<P_Product> p = context.P_Product.OrderByDescending(x => x.P_Id).ToList();
List<C_Category> c = context.C_Category.ToList();
var ao = new AdminObj()
{
p = p,
c = c
};
return View("Admin", new { c, p });
}
}
[HttpGet]
public ActionResult Admin()
{
using (var context = new sopingadbEntities())
{
List<P_Product> p = context.P_Product.OrderByDescending(x => x.P_Id).ToList();
List<C_Category> c = context.C_Category.ToList();
var ao = new AdminObj()
{
p = p,
c = c
};
return View(ao);
}
}
但在我看来,我犯了一个错误:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“对象”不包含“c”的定义
我肯定我一直在这样做,我是不是错过了什么
这是addwatch:
错误:
如果在视图中声明AdminObj为模型,则必须在返回参数中传递var ao
或
当前,在返回视图中,您正在以模型的形式返回匿名对象,这在您铸造视图时不起作用
提及您在视图中添加的@model
答复:
必须在本回答中提到的视图中添加此选项
@模型ProjectWeb.Controllers.HomeController.AdminObj
在控制器中:
[HttpGet]
public ActionResult Admin()
{
using (var context = new sopingadbEntities())
{
List<P_Product> p = context.P_Product.OrderByDescending(x => x.P_Id).ToList();
List<C_Category> c = context.C_Category.ToList();
var ao = new AdminObj()
{
p = p,
c = c
};
return View("Admin", new { c, p });
}
}
[HttpGet]
public ActionResult Admin()
{
using (var context = new sopingadbEntities())
{
List<P_Product> p = context.P_Product.OrderByDescending(x => x.P_Id).ToList();
List<C_Category> c = context.C_Category.ToList();
var ao = new AdminObj()
{
p = p,
c = c
};
return View(ao);
}
}
你们班的C组在哪里?错误是由于C_Category不包含属性C。类别列表在视图new{C,p}中传递,因此我使用Model.C作为类别列表,但它也传递p_产品列表C是单个C_类别,而不是列表。必须使用select从{c,p}获取c。您正试图将单个对象强制转换为列表。所以您需要List categories=Model.c.Selectx=>x.c.ToList;我从mvc end context.C_Category.Selectx=>x.ToList尝试了这个方法;但仍然是相同的错误尝试:List categories=Model.Selectx=>x.c.ToList;我将其更改为[HttpGet]public ActionResult Admin{using var context=new-sopingadbEntities{List p=context.p_Product.OrderByDescendingx=>x.p_Id.ToList;List c=context.c_Category.ToList;var ao=new AdminObj{p=p,c=c};return Viewao;}}但是仍然没有运气,这就是你提到要做的吗