我有两个看起来像这样的MVC模型:
public class OtherModel
{
[Required]
[Display(Name = "Another ID")]
public int id{ get; set; }
}
public class MyModel
{
[Required]
[Display(Name = "ID")]
public int id { get; set; }
public PlayerModel otherModel = new OtherModel ();
}
我的控制器有一个名为USE的[HttpPost]动作,如下所示:
[HttpPost]
public ActionResult Use(MyModel myModel)
{
/// myModel.otherModel.id is 0 here!!
}
此操作包含MyModel。当我的表单被发布时,otherModel变量包含id为id的值。现在,包含表单的视图被传递给MyModel并实际在页面上显示otherModel.id。问题是后期行动不是 正确地将表单数据编组到otherModel对象中,我不知道为什么。
另一个注意事项:当我检查帖子的表单数据头时,我清楚地看到otherModel.id带有我期望的值。
为什么这些数据在我的otherModel对象中没有正确显示?
提前谢谢你!
答案 0 :(得分:1)
您是否在Global.asax.cs中注册了活页夹?
public static void RegisterBinders(ModelBinderDictionary binders)
{
binders.Add(typeof(MyModel), new MyModelBinder());
// other binders
}
在Application_Start中调用它,如下所示:
protected void Application_Start()
{
RegisterBinders(ModelBinders.Binders);
}
PS:我以为你使用的是自定义模型绑定器。如果您使用自动绑定,请参阅您是否遵守命名约定。
答案 1 :(得分:0)
不要使用otherModel
行的新对象初始化PlayerModel otherModel = new OtherModel();
,而是使用属性public PlayerModel otherModel { get; set; }
。 otherModel
需要模型绑定器的属性设置器才能正确分配值。这可能还需要您在显示视图时更改填充otherModel
属性的方式 - 构造对象并在显示控制器方法或其他一些水合模型的函数中明确指定它。
答案 2 :(得分:0)
我有一个几乎相同的问题。对我来说,修复就像Matt提到的那样,使内部对象成为具有所需访问器的属性。
public class OuterModel
{
public OuterModel ()
{
AuxData= new InnerModel();
}
public InnerModel AuxData{ get; set; }
}
public class InnerModel
{
Int Id {get; set;}
}