[英]MVC model binding to nested classes
当我尝试创建一个新的'Flow'类时,嵌套类('Action')总是在控制器中返回null
所以我在类中有这样的类:
public class Flow
{
private Action actionField
private string nameField
private bool enabledField
...
}
public class Action
{
private ActionSchedule actionScheduleField
private ActionParameter actionParameterField
private nameField
}
public class ActionSchedule
...
并为“流量”创建一个单独的视图
@model ProjectZeus.Models.Flow
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.TextBoxFor(model => model.name, new { @placeholder = "Flow name" })
@Html.ValidationMessageFor(model => model.name)
@Html.LabelFor(model => model.enabled)
@Html.EditorFor(model => model.enabled)
@Html.ValidationMessageFor(model => model.enabled)
@Html.Partial("FlowAction")
...
然后是每个子类的部分视图
@model ProjectZeus.Models.FlowAction
@Html.TextBoxFor(model => model.name, new { @placeholder = "Action name" })
...
我已经尝试创建类的实例并调用视图 - 错误,
我已经尝试在视图中创建类的实例 - 错误,
我尝试过不使用PartialViews:
@Html.TextBoxFor(model => model.action.name, new { @placeholder = "Action name" })
我用谷歌搜索和谷歌googledddd但没有运气,请帮助!?
编辑:
实施客户模型绑定器似乎有点矫枉过正。 这个页面描述了同样的问题,但解决方案代码不会为我编译''当前上下文中不存在名称'helper''? - http://danielhalldev.wordpress.com/2013/08/23/partial-views-and-nested-mvc-model-binding/
EDIT2:
为简洁起见,我更改了模型定义 - 模型实际上是从xsd自动生成的:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class D53ESBFlow
{
private D53ESBFlowAction actionField;
[Required]
private string nameField;
...
private bool enabledField;
/// <remarks/>
public D53ESBFlowAction action
{
get
{
return this.actionField;
}
set
{
this.actionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
编辑3(凹凸):
看起来'binder'是创建属性而不是类对象?
你忘了{get; 组; 访问者对属性名称?
我与MVC 5,.NET 4.5,Visual Studio 2013有类似的问题。
这对我有用:添加一个构造函数,使包含的类得到实例化,使它们成为属性(而不是变量),如AntoineLev所说,并将类添加到Binding:
public class Flow
{
public Action actionField {get; set; }
public class Flow()
{
actionField = new Action(); // otherwise it shows up as null
}
}
在您的控制器中,在绑定中添加整个类:
public ActionResult Create([Bind(Include="action,name,enabled")] Flow flow)
{
...
}
你的旅费可能会改变。
}
我最终通过请求响应并按名称单独映射所有属性:
flow.action = new D53ESBFlowAction
{
name = Request["action.name"],
...
我有类似的麻烦,吉米博加德的这篇文章帮助了我。 文章在这里
看看生成的html会显示,在部分视图中,html不包含嵌套类的名称,因此默认情况下无法绑定它。 如上面的一个答案中给出绑定声明解决了问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.