【问题标题】:MVC Model Class not populated on post帖子中未填充 MVC 模型类
【发布时间】:2012-02-16 14:47:45
【问题描述】:

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

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

为什么这些数据在我的 otherModel 对象中没有正确显示?

提前谢谢你!

【问题讨论】:

  • 您可以发布进入控制器的表单标题吗?
  • 这也让我想知道你是否设置了 id 和另一个 id?
  • otherModel 真的是公共成员而不是属性吗?
  • @Jesse - 我现在没有确切的标题,事实上,与实际情况相比,上面的这些模型被简化了,但这也不起作用。标题肯定包含:“otherModel.id”和正确的值。事实上,我现在正在做的是解决这个问题:if(!int.TryParse(this.Request.Form["otherModel.id"], out value))。
  • 我认为你应该展示你的 Razor 代码,可能是你没有通过 Action 发送模型

标签: c# .net asp.net-mvc-3 forms post


【解决方案1】:

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

【讨论】:

  • 他从来没有提到他为他的模型制作了一个模型粘合剂,那为什么会有问题呢?
  • 你是对的。这是我的假设,但自定义绑定消除了很多麻烦,就像上面描述的那样。
【解决方案2】:

不要在PlayerModel otherModel = new OtherModel(); 行使用新对象初始化otherModel,而是使用属性public PlayerModel otherModel { get; set; }otherModel 需要模型绑定器的属性设置器来正确分配值。这可能还需要您更改在显示视图时填充 otherModel 属性的方式 - 构造一个对象并在显示控制器方法或其他一些水合模型的函数中显式分配它。

【讨论】:

    【解决方案3】:

    我遇到了几乎相同的问题。正如 Matt 提到的,我的解决方法是使内部对象成为具有所需访问器的属性。

    public class OuterModel 
    {
        public OuterModel ()
        {
            AuxData= new InnerModel();
        }
        public InnerModel AuxData{ get; set; }
    }
    
    public class InnerModel
    {
         Int Id {get; set;}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多