我正在尝试显示其中包含一些自定义类类型的属性的类。型号:
public class ComplexParent
{
public SimpleChild First { get; set; }
public SimpleChild Second { get; set; }
}
public class SimpleChild
{
public int Id { get; set; }
public string ChildName { get; set; }
public string ChildDescription { get; set; }
}控制器:
public ActionResult Testify(int id)
{
ComplexParent par = new ComplexParent();
par.First = new SimpleChild() { Id = id };
par.Second = new SimpleChild()
{
Id = id + 1,
ChildName = "Bob",
ChildDescription = "Second"
};
return View("Testify", par);
}
[HttpPost]
public ActionResult Testify(ComplexParent pComplexParent)
{
return View("Testify", pComplexParent);
}查看:
<% using (Html.BeginForm())
{%>
<fieldset>
<legend>Fields</legend>
<%: Html.EditorFor(x => x.First) %>
<br />
<%: Html.EditorFor(x => x.Second.ChildName)%>
<br/>
<br/>
<br/>
<% Html.RenderPartial("SimpleChild", Model.First); %>
<p>
<input type="submit" value="Watch me :-)" />
</p>
</fieldset>
<% } %>当让它正常工作时,我可以看到所有的数据。但是在post中,pComplexParent参数是空的(复杂类的两个属性都是空的)。可能我在这里遗漏了什么,但是我不能让它工作…小的增加:只显示名称编辑器的视图部件使第二个孩子不为空,并且名称设置为Bob。但我不明白如何仅使用EditorFor或DisplayFor方法来实现。
更新:感谢Darin Dimitrov,他亲切地检查了我的所有代码,并找到了导致这个问题的原因。确切的问题是,如果你使用的是显示模板,asp.net MVC2不会回发任何值,如果整个模板没有什么要回发的,对象是空的。我仍然在想如何获取数据,即使你不想编辑它。但是使用编辑器模板可以做到这一点,我现在已经用正确的数据填充了所有的对象。
发布于 2010-10-23 18:04:13
你的视图有点乱。您正在使用编辑器模板以及第一个子级的部分参数。表单中包含哪些字段并不是很清楚。我建议你只使用编辑器模板:
型号:
public class ComplexParent
{
public SimpleChild First { get; set; }
public SimpleChild Second { get; set; }
}
public class SimpleChild
{
public int Id { get; set; }
public string ChildName { get; set; }
public string ChildDescription { get; set; }
}控制器:
[HandleError]
public class HomeController : Controller
{
public ActionResult Testify(int id)
{
var par = new ComplexParent();
par.First = new SimpleChild() { Id = id };
par.Second = new SimpleChild()
{
Id = id + 1,
ChildName = "Bob",
ChildDescription = "Second"
};
return View(par);
}
[HttpPost]
public ActionResult Testify(ComplexParent pComplexParent)
{
return View(pComplexParent);
}
}查看:
<% using (Html.BeginForm()) { %>
<%: Html.EditorFor(x => x.First) %>
<%: Html.EditorFor(x => x.Second) %>
<input type="submit" value="Watch me :-)" />
<% } %>SimpleChild编辑器模板(~/Views/Home/EditorTemplates/SimpleChild.ascx):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeNs.Models.SimpleChild>" %>
<%: Html.HiddenFor(x => x.Id) %>
<%: Html.EditorFor(x => x.ChildName) %>
<%: Html.EditorFor(x => x.ChildDescription) %>现在,如果您希望为这两个子属性使用不同的编辑器模板,您可以在包含编辑器模板时指定它的名称:
<%: Html.EditorFor(x => x.First, "FirstChildEditor") %>它对应于~/Views/Home/EditorTemplates/FirstChildEditor.ascx,或者在模型中使用[UIHint]属性:
public class ComplexParent
{
[UIHint("FirstChildEditor")]
public SimpleChild First { get; set; }
public SimpleChild Second { get; set; }
}我的建议是使用而不是来使用Html.RenderPartial生成输入字段,因为它们的名称将是硬编码的,并且不会根据您的对象层次结构正确绑定。
https://stackoverflow.com/questions/4003261
复制相似问题