我有两个看起来像这样的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值包含0。现在,包含表单的视图将传递给MyModel,并实际上在页面上显示otherModel.id。问题是后期操作不
正确地将表单数据编组到otherModel对象中,我不知道为什么。

另一个注意事项:当检查帖子的表单数据标题时,我清楚地看到了otherModel.id和期望的值。

为什么此数据不能在我的otherModel对象中正确显示?

先感谢您!

最佳答案

您是否在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:我假设您正在使用自定义模型活页夹。如果您使用的是自动绑定,请查看您是否遵守命名约定。

10-07 19:23
查看更多