我有两个 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 ();
}
我的 Controller 有一个名为 USE 的 [HttpPost] 操作,如下所示:
[HttpPost]
public ActionResult Use(MyModel myModel)
{
/// myModel.otherModel.id is 0 here!!
}
此操作采用 MyModel。发布我的表单时,otherModel 变量的 id 值包含一个 0。现在,包含表单的 View 被传递给一个 MyModel 并实际在页面上显示 otherModel.id。问题是后行动不是 将表单数据正确编码到 otherModel 对象中,我不知道为什么。
另一个注意事项:当我检查帖子的表单数据标题时,我清楚地看到 otherModel.id 具有我期望的值。
为什么这个数据在我的 otherModel 对象中没有正确显示?
提前致谢!
最佳答案
您是否在 Global.asax.cs 中注册了 Binder ?
public static void RegisterBinders(ModelBinderDictionary binders)
{
binders.Add(typeof(MyModel), new MyModelBinder());
// other binders
}
这在 Application_Start 中调用如下:
protected void Application_Start()
{
RegisterBinders(ModelBinders.Binders);
}
PS:我假设您使用的是自定义模型 Binder 。如果您使用自动绑定(bind),请查看您是否遵守命名约定。
关于c# - 发布时未填充 MVC 模型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9313336/