Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return model from Partial View issue

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

like image 406
user2376512 Avatar asked May 15 '13 05:05

user2376512


1 Answers

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

like image 191
Kenneth Avatar answered Oct 27 '22 00:10

Kenneth