@Html.HiddenFor() in mvc 3 doesn't pass data to controller

2.1k Views Asked by At

I have a class named "AirLineSession":

    public ExtendedList listCo { get; set; }
    public ExtendedList listBa { get; set; }

    public bool SortbyRating { get; set; }
    public AirLineSession()
    {
        listCo = new ExtendedList();
        listBa = new ExtendedList();
    }

In my view I have:

@Html.HiddenFor(m => m.listBa)
@Html.HiddenFor(m => m.listCo)
@Html.DropDownListFor(a => a.SortbyRating, new[] { new SelectListItem { Text = "Sort by rating", Value = "true" }, new SelectListItem { Text = "Sort by frice", Value = "false" } })

When I summit this view, only data of SortByRating is passed to the model in Controller, listBa and listCo aren't passed. I don't know why.
Anyone help me, thanks.

2

There are 2 best solutions below

0
On

Could you post the code of ExtendedList class? The reason is the asp.net mvc does not know how to create all Hiddens for the ExtendedList complex type. In this case, you should add hiddens for each field of object and collection for both collections, for sample:

@for(var i = 0; i < Model.listCo.Lenght; i++)
{
    @Html.HiddenFor(model => model.listCo[i].Property1)
    @Html.HiddenFor(model => model.listCo[i].Property2)
    @Html.HiddenFor(model => model.listCo[i].Property3)
}

And also:

@for(var i = 0; i < Model.listBa.Lenght; i++)
{
    @Html.HiddenFor(model => model.listBa[i].Property1)
    @Html.HiddenFor(model => model.listBa[i].Property2)
    @Html.HiddenFor(model => model.listBa[i].Property3)
}
0
On

If you are using For ended html helpers, make sure you have passed their values by model to the related view. But if not, you should put values to some dynamic tools like ViewBag and then use the follwing code:

@Html.Hidden("listBa", ViewBag.listba)
@Html.Hidden("listCo", ViewBag.listco)