POST之后出现NullReferenceException [英] NullReferenceException after POST

查看:54
本文介绍了POST之后出现NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有使用模型填充列表的dropDownlist的表单,呈现了视图.问题是,当我按下提交"按钮时,将引发Model的空指针异常.我想接收在发布操作"中选择的值.

I've got a form that has a dropDownlist using the Model to fill the list, the view is rendered. The issue is that when i press the submit button, a null pointer exception for Model is thrown. I want to receive the value selected in the 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();
    }

视图:这是我在 Model.ClientList

@using (Html.BeginForm())
{
    @Html.DropDownListFor(item => item.SelectedClient, Model.ClientList, "Select Client")
    <input type="submit" value="Aceptar"/>
}

推荐答案

[HttpPost] 动作方法中,您正在调用没有任何viewmodel的View()方法.因此,视图内的Model属性为null.解决方案就是简单地调用View并传入 BillViewModel .

In the [HttpPost] action method, you are invoking the View() method without any viewmodel. Therefore the Model property inside the view is null. The solution is simply to invoke View and passing in the BillViewModel.

例如:

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

这篇关于POST之后出现NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆