在我的应用程序中使用了这些,但遇到了这个问题。
我有这两个模型:
public class vwLkUpDepartmentCategory
{
[Key]
public int DepartmentCategoryID { get; set; }
public string DepartmentCategory { get; set; }
public Byte IsActive { get; set; }
}
public class vwDimDepartments
{
[Key]
public Int64 DepartmentID { get; set; }
public string DepartmentName { get; set; }
public int DepartmentCategoryID { get; set; }
public string DepartmentCategory{ get; set; }
public string Departments { get; set; }
public Byte IsActive { get; set; }
}
在控制器中我为viewbag中的值设置下拉列表
ViewBag.DepartmentDropDown = new SelectList(db.vwLkUpDepartmentCategory.Where(x => x.IsActive == 1).ToList(), "DepartmentCategoryID", "DepartmentCategory");
在视图中我有
<div>@Html.LabelFor(model => model.DepartmentCategoryID)</div>
<div>@Html.DropDownListFor(model => model.DepartmentCategoryID, new SelectList(ViewBag.DepartmentDropDown, "DepartmentCategoryID", "DepartmentCategory"), "", new { @class = "dropdown", id = "txtDepartmentCategoryID" })</div>
<div>@Html.ValidationMessageFor(model => model.DepartmentCategoryID, "", new { @class = "text-danger" })</div>
但是当我运行它时,我收到一个错误说
DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'DepartmentCategoryID'.
这是因为我将departmentId作为视图中的键值吗?
如果我没有在视图中明确定义departmentCategoryID字段,它将采用第一个离开并始终使用它。
最好的方法是什么?
答案 0 :(得分:0)
在Controller ::
上试试这个 ViewBag.DepartmentCategoryID= new SelectList(db.vwLkUpDepartmentCategory.Where(x => x.IsActive == 1).ToList(), "DepartmentCategoryID", "DepartmentCategory");
在View ::
上 <div>@Html.LabelFor(model => model.DepartmentCategoryID)</div>
<div>@Html.DropDownListFor(model => model.DepartmentCategoryID, SelectList(ViewBag.DepartmentCategoryID, new { @class = "dropdown", id = "txtDepartmentCategoryID" })</div>
<div>@Html.ValidationMessageFor(model => model.DepartmentCategoryID, "", new { @class = "text-danger" })</div>