Search code examples
asp.netasp.net-mvcasp.net-mvc-4asp.net-mvc-viewmodel

MVC ViewModel returns ArgumentNullException


I am having a problem returning values to the controller when using a ViewModel.

For clarity I have simplified the code below where the original has many more fields.

When the page is loaded, the value in the hidden field is as expected. However when the form is submitted the value in the field is not being sent and instead I get an ArgumentNullException.

Please can you advise on what I am doing wrong.

View

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

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


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

}

Model

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

Controller

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

Solution

  • 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.