我有一个带有dropDownlist的表单,使用Model来填充列表,呈现视图。问题是当我按下提交按钮时,会抛出Model的空指针异常。我想收到Post Action中选择的值。
这是我的代码:
型号:
public class BillViewModel
{
public List<SelectListItem> ClientList { get; set; }
public int SelectedClient { get; set; }
}
控制器:
public ActionResult Index()
{
var billRepo = new BillRepo();
var bill = new BillViewModel {ListProducts = billRepo.GetAllProducts()};
bill.ClientList = new List<SelectListItem>();
List<Client> allClientList = billRepo.GetAllClients();
foreach (Client client in allClientList)
{
var item = new SelectListItem() { Value = client.ClientId.ToString(), Text = client.Name };
bill.ClientList.Add(item);
}
ViewBag.ClientSelect = new SelectList(billRepo.GetAllClients(), "value", "text", bill.SelectedClient);
bill.SelectedClient = 1;
return View(bill);
}
[HttpPost]
public ActionResult Index(BillViewModel billViewModel)
{
return View();
}
查看:模型
@using (Html.BeginForm())
{
@Html.DropDownListFor(item => item.SelectedClient, Model.ClientList, "Select Client")
<input type="submit" value="Aceptar"/>
}
答案 0 :(得分:3)
在您的POST操作中,您将返回与GET操作中相同的索引视图。但是你没有将任何模型传递给这个视图。这就是你获得NRE的原因。您的视图必须呈现下拉列表,您需要填充其值,就像您在GET操作中一样:
[HttpPost]
public ActionResult Index(BillViewModel billViewModel)
{
bill.ClientList = billRepo
.GetAllClients()
.ToList()
.Select(x => new SelectListItem
{
Value = client.ClientId.ToString(),
Text = client.Name
})
.ToList();
return View(billViewModel);
}
注意视图模型是如何传递给视图的,以及ClientList
属性(您的下拉列表绑定到的属性)如何用值归档。