以mvc形式标记模型
本文关键字:模型 mvc | 更新日期: 2023-09-27 18:22:05
我有一个表单,它有一个dropDownlist,使用Model来填充列表,视图被渲染。问题是,当我按下提交按钮时,会抛出Model的空指针异常。我想接收在后操作中选择的值。
这是我的代码:
型号:
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"/>
}
在POST操作中,您将返回与GET操作中相同的Index视图。但您并没有将任何模型传递给此视图。这就是你获得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
属性(下拉列表绑定到该属性)是如何使用值进行归档的。