Reputation: 393
I have the following model :
public class ContratoDetailsViewModel
{
[StringLength(50)]
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$")]
[DisplayName("E-Mail Adm.")]
public string emailAdm { get; set; }
}
public class ContratoDetailContainerViewModel
{
public ContratoDetailsViewModel contrato { get; set; }
public IList<ContratoModels.CCasinoViewModel> ccasinos { get; set; }
}
public class CCasinoViewModel
{
public short codigo { get; set; }
public List<SelectListItem> listCasinos { get; set; }
}
the following view :
@model ContratoModels.ContratoDetailContainerViewModel
@{
...
}
@using (Html.BeginForm(new { currentaction = ViewBag.mode }))
{
...
@Html.EditorFor(m => m.contrato.emailAdm, state1)<br />
@Html.EditorFor(m => m.ccasinos,"test")
<input type="submit" value="Save" />
}
in the folder "EditorTemplates" i have a template called "test.cshtml" :
@model List<ContratoModels.CCasinoViewModel>
@for (int i = 0; i < Model.Count(); i++)
{
@Html.DropDownListFor(m => m[i].codigo,Model[i].listCasinos)
}
My Controller post action is like this :
[HttpPost]
public ActionResult Details(ContratoModels.ContratoDetailContainerViewModel model, FormCollection form)
{
var contrato = model.contrato;
var casinos = model.ccasinos;
}
Before send the view ccasinos,codigo and listCasinos are initialised when i am in debug mode i see the value of them... the form display work like a charm. BUT ... when i submit the form the model.ccasinos is always null !! why ? thank you very much for your reply.
note : I use a EditorFor with the child of my main model but if there is a better solution for display and submit with MCV 3 I am interested ...
Upvotes: 0
Views: 4153
Reputation: 1039588
Try replacing:
@Html.EditorFor(m => m.ccasinos, "test")
with this:
@Html.EditorFor(m => m.ccasinos)
and then rename your test.cshtml
template to CCasinoViewModel.cshtml
and replace its contents with this:
@model CCasinoViewModel
@Html.DropDownListFor(x => x.codigo, Model.listCasinos)
Because the editor template is now named the same way as the type of the list, ASP.NET MVC will automatically render it for each element of this list so that you don't have to write loops.
Also you can safely remove the FormCollection
argument from your action. It's completely useless when you are working with view models:
[HttpPost]
public ActionResult Details(ContratoModels.ContratoDetailContainerViewModel model)
{
var contrato = model.contrato;
var casinos = model.ccasinos;
...
}
Upvotes: 2