从部分视图问题返回模型

use*_*512 5 asp.net-mvc asp.net-mvc-4

我创建了一个局部视图(即使是编辑器模板),我将一个子模型传递给视图,但是,当我单击"提交"时,我总是从局部视图中获得"null".除了子模型1之外,我可以获得Main模型的属性值.

主要模型

public class PetModel
{
  public string name {get; set;}
  public long SpeciesID {get; set;}
  public long BreedID {get; set;}
  public Calendar DOB {get; set;} 
} 
Run Code Online (Sandbox Code Playgroud)

子模型

public class Calendar
{
    public string Year{get; set;}
    public string Month{get; set;}
    public string Day{get; set;}
}
Run Code Online (Sandbox Code Playgroud)

主视图

    @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" />
   }
Run Code Online (Sandbox Code Playgroud)

编辑模板

@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>())
Run Code Online (Sandbox Code Playgroud)

"CatchPetContent"动作

[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));

}
Run Code Online (Sandbox Code Playgroud)

当我调试它时,"Model.DOB"始终为null

Ken*_*eth 6

您应该将子属性添加为操作的额外参数:

[HttpPost]
public ActionResult CatchPetContent(PetModel Model, Calendar Bob)
{      
    ** snip **
}
Run Code Online (Sandbox Code Playgroud)

默认的ModelBinder不嵌套对象.但是,如果将其作为第二个参数包含在内,它会找到值.

如果你想嵌套它们,你必须创建自己的模型绑定器.

以下问题有一个类似的问题:在ASP.Net MVC中从视图传递到模型时列表计数为空