Passing IEnumerable or list Model to Controller using HttpPost

asp.net-mvc-3, c#

Solution

There are a few things you need to fix. First for your models, make everything properties. Do not use fields.

Models:

public class SpesaTrasportoView
{
    public int SPESATRASPORTOVIEW_ID { get; set; }
    public decimal PREZZO { get; set; }
    public string DESCRIZIONE { get; set; }
}

public class SpeseTrasportoView
{
    public List<SpesaTrasportoView> SpeseTrasportoModello { get; set; }
}

Now, change the for loop in the view so that it looks like this:

@for (int i = 0; i < Model.SpeseTrasportoModello.Count; i++)
{
    var item = Model.SpeseTrasportoModello[i];

    <div class="editor-field">
        <input type="text" 
               name="SpeseTrasportoModello[@i].PREZZO" 
               value="@item.PREZZO" />
    </div>
}

The key thing you need to know is the input name format. It should have the name of the property that is inside your model (your list) with an index in square brackets and then the name of the property that this input is for (e.g. PREZZO).

Problem

I have this problem: My models ``` public class SpesaTrasportoView { public int SPESATRASPORTOVIEW_ID; public decimal PREZZO; public string DESCRIZIONE; } public class SpeseTrasportoView { public List<MvcCart.Models.SpesaTrasportoView> SpeseTrasportoModello { get; set; } //public IList<string> Spese { get; set; } } ``` My view ``` @model MvcCart.Models.SpeseTrasportoView @{ ViewBag.Title = "Spese Trasporto"; int counter = 0; } <div class="form-content"> <h2>Spese Trasporto</h2> <p> Modifica e gestisci gli importi delle spese di trasporto. </p> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { <div class="data-content"> <fieldset> <legend>Informazione Spese Trasporto</legend> @for (int i = 0; i < Model.SpeseTrasportoModello.Count; i++) { <div class="editor-field"> @Html.TextBoxFor(m => m.SpeseTrasportoModello.ToList()[i].PREZZO) </div> } <p> <input type="hidden" value="@ViewBag.FormStatus" id="Action" name="Action"/> <input type="submit" value="Salva" id="Salva" name="Salva"/> </p> </fieldset> </div> } </div> ``` My controller ``` [HttpPost] public ActionResult SpeseTrasporto(SpeseTrasportoView model) { //model.SpeseTrasportoModello is ever NULL :((((( return View(); } ``` When I submit the model.SpeseTrasportoModello is null! why mvc3 don't bind the data????

Original source