Techonthenet
Techonthenet

Reputation: 157

Model is Null in Httppost mvc

My Model is

public class IssueEntryModel
{
    public IEnumerable<SelectListItem> OrderNumbers { get; set; }
    public string SelectedWorkOrder { get; set; }
    public string MaterialCode
    {
        get; set;
    }
    public List<GroupedIssueData> MaterialData { get; set; }
}

And the view is

@model InventoryEasy15.Models.IssueEntryModel

@{
    var issueData = Model.MaterialData;
    var workorders = Model.SelectedWorkOrder;
}
@using (Html.BeginForm("SaveIssueEntry", "IssueMaster",  FormMethod.Post, new { id = "issueEntryForm" }))
{
    @for (int i = 0; i < issueData.Count(); i++)
    {
        <tr>
            <td>@issueData[i].MaterialCode</td>
            <td>@issueData[i].MaterialDescription</td>
            <td>@issueData[i].Unit</td>
            <td>@issueData[i].ReqQty</td>
            <td>@Html.TextBoxFor(m => issueData[i].IssueQty, new { style = "width:70px" })@Html.ValidationMessageFor(m => issueData[i].IssueQty)</td>
            <td class="text-center">@Html.CheckBoxFor(m => issueData[i].isSavings)</td>
        </tr>
    }

And I have post method as

public ActionResult SaveIssueEntry(IssueEntryModel model)
{
    var result = new Dictionary<string, string>();

And the get contains the details to fill the view as

//Method Get the material details based on the work order id
public async Task<ActionResult> GetWorkOrderMaterialDetails(IssueEntryModel m)
{

During post to a new method , the model is becomes null, Any thoughts?

Upvotes: 0

Views: 154

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239440

Razor uses the expression passed to the HTML helpers in order to build the proper name for the inputs that will allow the modelbinder to bind them properly on post. That means the expression needs to match the access method of the property exactly. By saving Model.MaterialData to the issueData variable and utilizing that, you're disrupting this. In other words, you're ending up with inputs named like issueData[0].IssueQty, instead of MaterialData[0].IssueQty. The modelbinder doesn't know what to do with issueData on post, because nothing on your model matches that.

Long and short, your textbox needs to be declared like:

@Html.TextBoxFor(m => m.MaterialData[i].IssueQty, ...)

Similarly for your checkbox:

@Html.CheckBoxFor(m => m.MaterialData[i].isSavings)

Upvotes: 1

Related Questions