ASP.NET MVC - 对象没有通过控制器传递到VIew。

问题描述 投票:0回答:1

我的 "视图 "里有这个。

  @{ 
      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 });
    }
}

但在我的视图中我得到一个错误:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'c'.

我相信我一直都是这样做的,我是不是错过了什么?

下面是加表。

enter image description here

错误:

enter image description here

c# asp.net-mvc
1个回答
1
投票

如果你声明 AdminObj 作为视图中的模型,您必须通过 var ao 反过来

当前你正在返回 anonymous object 在返回视图中作为模型,而在视图中却不能工作,因为你投下了

在视图中提到您添加了什么作为@model

答案延伸。

不得不在本答案中提到的视图中添加这个。

@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(ao);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.