MVC ViewModel返回ArgumentNullException

时间:2016-04-15 14:05:06

标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-viewmodel

使用ViewModel时,我在向控制器返回值时遇到问题。

为了清楚起见,我简化了下面的代码,其中原始字段有更多字段。

加载页面时,隐藏字段中的值与预期一致。但是,当提交表单时,字段中的值不会被发送,而是我得到一个ArgumentNullException。

请告诉我我做错了什么。

查看

@model Project.Models.SCView
@using (Html.BeginForm("ScorecardEdit"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    @Html.HiddenFor(model => model.FV.ID)


    <input type="submit" value="Save" />

}

模型

public class FixView
{
    public int ID { get; set; }

    [DisplayFormat(DataFormatString = "{0:ddd dd/MM/yyyy}")]
    public DateTime MatchDate { get; set; }

}

public class SCView
{
    public FixView FV { get; set; }

    public SCView()
    {
        this.FV = new FixView();
    }
}

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ScorecardEdit(SCView ReturnSC)
{
}

1 个答案:

答案 0 :(得分:2)

The code that you have should be working as MVC should be able to map your FV.ID property as expected as the HiddenFor() helper will generate the proper names to handle mapping it :

enter image description here

Using the same code that you provided, the debugger demonstrated the following after submitting the form :

enter image description here

The issue here sounds like you have a few other properties, possibly collection-based ones that use the DropDownListFor() helpers that have collections which are not posted to the server, so when you attempt to use the model you have to render populate one of those helpers, you are getting your ArgumentNullException.