Skip to main content
 首页 » 编程设计

c#之POST 后出现 NullReferenceException

2024年02月13日13itcoder

我有一个表单,它有一个 dropDownlist,使用模型来填充列表,呈现 View 。问题是当我按下提交按钮时,会抛出 Model 的空指针异常。我想接收在 Post Action 中选择的值。

这是我的代码:

型号:

public class BillViewModel 
{ 
    public List<SelectListItem> ClientList { get; set; } 
    public int SelectedClient { get; set; } 
} 

Controller Action :

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(); 
    } 

View :这是我在 Model.ClientList

中得到空指针异常的地方
@using (Html.BeginForm()) 
{ 
    @Html.DropDownListFor(item => item.SelectedClient, Model.ClientList, "Select Client") 
    <input type="submit" value="Aceptar"/> 
} 

请您参考如下方法:

在 [HttpPost] 操作方法中,您在没有任何 View 模型的情况下调用 View() 方法。因此, View 内的 Model 属性为空。解决方案很简单,就是调用 View 并传入 BillViewModel。

例如:

[HttpPost] 
public ActionResult Index(BillViewModel billViewModel) 
{ 
    return View(billViewModel); 
}