I have created a partial view (even though the editor template), I pass a sub model to the view, however, when I clicked "submit", I always get "null" from the partial view. I can get Main model's properties values except the sub model one.
Main Model
public class PetModel
{
public string name {get; set;}
public long SpeciesID {get; set;}
public long BreedID {get; set;}
public Calendar DOB {get; set;}
}
Sub Model
public class Calendar
{
public string Year{get; set;}
public string Month{get; set;}
public string Day{get; set;}
}
Main View
@model Application.Models.PetModel
@using (Html.BeginForm("CatchPetContent", "Quote",Model))
{
@Html.TextBoxFor(x => x.Name)
@Html.DropDownListFor(x=>x.SpeciesID,new List<SelectListItem>(),"select")
@Html.DropDownListFor(x=>x.BreedID,new List<SelectListItem>(),"select")
@Html.EditorFor(Model => x.DOB)
<input type="submit" value="submit" />
}
Editor template
@model Application.Models.Calendar
@Html.DropDownListFor(Model => Model.Day, new List<SelectListItem>())
@Html.DropDownListFor(Model => Model.Month,new List<SelectListItem>())
@Html.DropDownListFor(Model => Model.Year, new List<SelectListItem>())
"CatchPetContent" action
[HttpPost]
public ActionResult CatchPetContent(PetModel Model)
{
PetModel pet = new PetModel();
pet.Name = Model.Name;
pet.SpeciesID = Model.SpeciesID;
pet.BreedID = Model.BreedID;
pet.DOB = Model.DOB;// always null
RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
redirectTargetDictionary.Add("Controller", "Home");
redirectTargetDictionary.Add("Action", "Index");
return new RedirectToRouteResult(new RouteValueDictionary(redirectTargetDictionary));
}
When I debugged it, "Model.DOB" is always null
You should add the sub-property as an extra parameter on your action:
[HttpPost]
public ActionResult CatchPetContent(PetModel Model, Calendar Bob)
{
** snip **
}
The default ModelBinder doesn't nest the objects. It does however find the values if you include it as a second parameter.
If you want to nest them, you'd have to create your own modelbinder.
The following question had a similar issue: List count empty when passing from view to model in ASP.Net MVC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With