我创建了一个局部视图(即使编辑器模板),我将一个子模型传递给该视图,但是,当我单击“提交”时,我总是从部分视图。除了子模型之外,我可以获取Main模型的属性值。从部分视图问题返回模型
主要型号
public class PetModel
{
public string name {get; set;}
public long SpeciesID {get; set;}
public long BreedID {get; set;}
public Calendar DOB {get; set;}
}
子型号
public class Calendar
{
public string Year{get; set;}
public string Month{get; set;}
public string Day{get; set;}
}
主视图
@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" />
}
编辑模板
@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” 行动
[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));
}
当我调试它, “Model.DOB” 总是空
你是对的,但我已经将初始方法添加到每个下拉列表中,并且仍然为空。在我点击“提交”之前,我已经从下拉列表中选择了值,但是,一旦我点击了提交按钮,嵌套模型“日历”就会被指定为“null”。我已经在DefaultBuilder中调试了“SetProperty”方法,对象的值始终为空 – user2376512
尝试使用Fiddler检查项目的值以查看表单值实际上是否被传回服务器。此外,HTML是什么样的一年,是模型绑定它应该有一个像DOB.Year这样的名称,如果它不,那么它不会被绑定。 –
来自提琴手我可以找到下面的名称字符串=测试&SpeciesID = 2和BreedID = 7和DOB.Day = 23和DOB.Month = 05和DOB.Year = 2010 – user2376512