我试图在部分视图中在搜索框中添加一个列表,但我总是得到System.NullReferenceException。当我作为单独的视图保持时,类似的选项正在工作。通过List时,我不是我做错了什么? 以下是来自视图和控制器的片段:
1] _layout.cshtml:
<div class="row">
@Html.Partial("SearchBarPartial2", Model)
</div>
2] SearchPartialView2.cshtml:
<div class="form-group">
@using (Html.BeginForm("SearchBarPartial2", "Search"))
{
@Html.LabelFor(m => m.CompanyList, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(
m => m.CompanyList,
new SelectList(Model.CompanyList, "fldt", "Value", Model.CompanyList.First().Value),
new { @class = "form-control" }
)
</div>
}
</div>
3] SearchController.cs:
public ActionResult SearchBarPartial2(cmpnytable cmpnytable1)
{
List<Company> objcompany = new List<Company>();
objcompany = GetCompanyList();
SelectList objlistofcompanytobind = new SelectList(objcompany, "ID", "Name", 0);
cmpnytable1.CompanyList = objlistofcompanytobind;
return View(cmpnytable1);
}
答案 0 :(得分:0)
您的下拉列表声明已显示错误证据:
@Html.DropDownListFor(m => m.CompanyList, new SelectList(Model.CompanyList, "fldt", "Value", Model.CompanyList.First().Value), new { @class = "form-control" })
正如斯蒂芬所说,你被赋予了指向CompanyList
的模型绑定表达式,它成为了要呈现的所有选项标签的源。将SelectList
项作为绑定目标和选项列表的来源传递是没有意义的。
要解决此问题,请将具有整数/字符串类型的其他模型属性用于保存DropDownList
选择结果,如下所示:
// Model
public class cmpnytable
{
// other properties here
public int SelectedId { get; set; }
}
// View
@model myproj.Models.cmpnytable
@Html.DropDownListFor(m => m.SelectedId, Model.CompanyList, new { @class = "form-control" })
由于CompanyList
本身作为SelectList
传递给视图,因此在视图上创建SelectList
的新实例毫无用处。