【问题标题】:WebApplication.Models.Category instead of valueWebApplication.Models.Category 而不是值
【发布时间】:2022-02-24 03:34:15
【问题描述】:

我想在我的Insert 视图中添加一个DropDownList

控制器:

公共动作结果创建() { ViewBag.CategoryList = new SelectList(Category.GetCategories()); 返回视图(“插入”,新类别()); }

查看:

@Html.DropDownListFor(model => model.Category, (IEnumerable) (ViewBag.CategoryList), “选择类别”, htmlAttributes: new { @class= "form-control" })

Category 类只有一个名为 Titlestring 字段。我没有得到Title 的值,而是得到WebApplication.Models.Category

【问题讨论】:

  • return View("Insert", new Category()) 语句中,您将Category 类的新实例绑定到剃刀页面的model 属性。这意味着model 属性的类型是Category 本身。所以它看起来有点奇怪,比如model.Category,因为模型不应该有这个属性,但应该有model.Title。您能否澄清一下您如何在页面上声明@model。
  • @Kitta 我有一个Product 模型,它有一个Category 属性。页面上的@model@model WebApplication1.Models.Product
  • 这意味着您传递给页面的实例与模型声明之间存在差异。我想,首先你需要在控制器方法中使用return View("Insert", new Product()) 之类的东西。之后,您可以通过 model.Category.Title 语句访问 Title 属性,或使用 m => m.Category 将下拉框绑定到 Category 属性。

标签: c# asp.net-mvc


【解决方案1】:

检查Title 是否被定义为属性,而不是数据绑定的字段。

然后尝试以下操作:

public ActionResult Create()
{
    ViewBag.CategoryList = Category.GetCategories();
    return View("Insert", new Product()); 
}

Insert 视图中:

@using WebApplication1.Models @* Category namespace *@
@model WebApplication1.Models.Product

@{   
    IEnumerable<Category> categories = (IEnumerable<Category>)ViewBag.CategoryList;
}

@Html.DropDownListFor(m => categories.GetEnumerator().Current,
          categories.Select(d =>
          {
              return new SelectListItem() { Text = d.Title, Value = d.Title };
          }),
          "Select Category", new { @class = "form-control" })

【讨论】:

  • @EL02:您能解释一下为什么将Category 的一个实例作为视图模型传递给Insert 视图吗?看起来很奇怪。传递所有类别的列表会更合乎逻辑,而不是使用ViewBag
  • 我也有点迷失在这里。第一次处理下拉列表。我有一个 Product 模型,它有一个字符串 Category 属性。页面上的@model@model WebApplication1.Models.Product。我想将所选选项的值传递给model.Category
  • @EL02:好的。然后在 Create 方法中,只需将 Category.GetCategories(); 替换为填充 ViewBag.CategoryList 集合的代码。它的类型应该是List&lt;Category&gt;
  • 我收到此错误:Unable to cast object of type 'System.Web.Mvc.SelectList' to type 'System.Collections.Generic.IEnumerable1[WebApplication1.Models.Category]'. 是的,我也更换了控制器
  • @EL02:这是因为您在Create 方法中有ViewBag.CategoryList = new SelectList(Category.GetCategories()); 行。我建议用ViewBag.CategoryList = Category.GetCategories(); 替换这一行。我想Category.GetCategories() 创建了一个 List.
猜你喜欢
  • 2018-04-05
  • 2011-10-18
  • 1970-01-01
  • 2015-08-19
  • 2020-05-13
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多