Search code examples
asp.net-mvcasp.net-mvc-5

Submitting Form in MVC 5 model is null in controller post method


After post I am getting List in model is null my model is has a property which is the list of vwLog.

public class CreateLogViewModel
{
    public List<vwLog> LogData;
}

In view I used that model and used foreach loop to assign the value in text control

@model CreateLogViewModel

@using (Html.BeginForm("CreateLog", "Log", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    foreach (var item in Model.LogData)
    {
        <table>            
            <tr>
                <td>
                    @Html.HiddenFor(modelItem => item.LogID)
                    @Html.TextBoxFor(modelItem => item.AgencyBillingCode)
                </td>
                <td>
                    @Html.TextBoxFor(modelItem => item.LicenseNumber)
                </td>
            </tr>
        </table>
    }
    <div class="col-xs-12" align="center">
        <input class="btn btn-default" type="submit" name="Submit" value="Save" id="Submit">
    </div>
}

My Controller is

In Get method I am assigning the value in LogData object which is the collection of vwlog.

public ActionResult CreateLog(CreateLogViewModel model)
{
   model.LogData = GetDate();
   return View(model);
 }

I update some value of the list on the screen and try to save that, but I am getting model.LogData null in Post.

[HttpPost]
public ActionResult CreateLog(CreateLogViewModel model, string submit)
{
    if (model.LogData != null)
    { 
        do this...
    }
}

I update some value of the list on the screen and try to save that, but I am getting model.LogData null in Post. model is not null, but the collection object is null. Please let me know where I am wrong.


Solution

  • The MVC model binder doesn't work with class fields:

    public class CreateLogViewModel
    {
        // This is a field
        public List<vwLog> LogData;
    }
    

    you must use properties:

    public class CreateLogViewModel
    {
        // This is a property
        public List<vwLog> LogData { get; set; }
    }
    

    NOTE: You also need to make sure your vwLog type has public read-write properties for it to work.