c# - 发布时未填充 MVC 模型类

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

我有两个 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/

相关文章:

.net - Json 数据有 {d :"data"}

c# - 在 WPF 窗口中显示时间

c# - 尝试保存实体时 ModelState.isvalid 为 false,错误表示相关实体中需要一个字段

asp.net-mvc-3 - asp.net mvc 3 中的自定义错误页面

c# - 获取 datacontext.ExecuteQuery 返回的动态对象的属性

c# - 在 C# 中选择以 "NVH"而不是 "NVHE"开头的文件名

c# - 下载多个文件的更快方法

c# - 在设计时显示 MultilineStringEditor 以编辑编辑控件的行?

c# - 使用 ASP.NET C# 在面板控件中迭代动态 FileUpload 控件集合

c#:如何使用默认空格+一组附加分隔符拆分字符串?