【问题标题】:MVC-Post Page Partially - Model Binding FailsMVC-Post Page Partially - 模型绑定失败
【发布时间】:2017-04-24 21:03:26
【问题描述】:

我正在尝试发布页面的一部分并将其绑定到控制器上的视图模型。我的SearchVM 的编辑器模板:

@Html.TextBoxFor(model => model.TestText, new { @class = "form-control ",
                 @placeholder = "TEXT" , @id="test" })
<input type="submit" value="Submit" />

索引.cshtml:

@using (Html.BeginForm("Search", "Pencil", FormMethod.Post, 
                       new { enctype = "multipart/form-data" }))
{
   @Html.EditorFor(model => model.SearchVM);
}

控制器:

  public ActionResult Search(SearchVM vm)
  {
     // ...
  }

当我在testText 文本框上输入内容并点击提交时,我到达操作搜索但vm.TestText 为空,我无法将表单字段从编辑器模板绑定到视图模型。任何想法?

【问题讨论】:

  • 公共类 SearchVM { 公共字符串 TestText { 获取;放;现在我正在尝试使用 Ajax.BeginForm 而不是 HTML,BeginForm 但结果相同
  • 我认为这是因为您覆盖了文本框 ID。当您发布表单时,输入的 ID 必须与模型属性名称相对应,以便默认模型绑定器工作。尝试删除这个:@id="test"
  • 试过了,结果一样
  • 好的,然后在发送 post 请求时检查浏览器中的网络选项卡 - 请求正文是什么样的?
  • 感谢您的提示,帮助我找到了问题

标签: c# asp.net-mvc razor model-binding mvc-editor-templates


【解决方案1】:

发生这种情况是因为作为@model 传递给您的视图的类包装了SearchVM 类,并且当您调用@Html.EditorFor(model =&gt; model.SearchVM) 时,它会呈现带有前缀SearchVM 的输入:

<input id="SearchVM_TestText" name="SearchVM.TestText" value="" ... />

反过来,当发回控制器时,ModelBinder 将无法将其反序列化为 SearchVM

你可以做的是使用this EditorFor重载:

@Html.EditorFor(model => model.SearchVM, "_SearchVM", "");

其中_SearchVM 是您的编辑器模板的名称。将"" 作为htmlFieldName 参数传递将删除输入中不需要的SearchVM 前缀。

【讨论】:

  • @user2026343 如果此答案解决了您的问题,请帮 Stack Overflow 一个忙并将其标记为已接受 :)
猜你喜欢
  • 2020-03-23
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多