1

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.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
Reena
  • 75
  • 2
  • 11
  • Not relevant to question, but for security I strong suggest using @Html.AntiForgeryToken() in your view and authenticate the token in your controller with [ValidateAntiForgeryToken()] – Chad Jun 17 '16 at 15:49
  • You cannot use a `foreach` loop (refer the dupe) and you model must contain properties, not fields as NightOwl888 has indicated. –  Jun 17 '16 at 23:14

1 Answers1

5

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.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • Hey thanks... It works I did couple of changes including converting that to property. So now model public List LogData { get; set; } and controller is -- List LogList = new List(); LogService service = new LogService(); LogList = getdata() model.LogData = LogList; – Reena Jun 17 '16 at 16:32