我有一个具有两个简单方法的控制器:

UserController 方法:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Details(string id)
{
 User user = UserRepo.UserByID(id);

 return View(user);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Details(User user)
{
 return View(user);
}

然后有一个简单的视图来显示详细信息:

<% using (Html.BeginForm("Details", "User", FormMethod.Post))
   {%>
 <fieldset>
  <legend>Userinfo</legend>
  <%= Html.EditorFor(m => m.Name, "LabelTextBoxValidation")%>
  <%= Html.EditorFor(m => m.Email, "LabelTextBoxValidation")%>
  <%= Html.EditorFor(m => m.Telephone, "LabelTextBoxValidation")%>
 </fieldset>
 <input type="submit" id="btnChange" value="Change" />
<% } %>

如您所见,我使用编辑模板“ LabElTextBoxValidation”:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%= Html.Label("") %>
<%= Html.TextBox(Model,Model)%>
<%= Html.ValidationMessage("")%>

显示用户信息没有问题。该视图呈现完美的用户详细信息。当我提交表单时,对象用户会丢失。我在“返回视图(用户)”行上进行了调试。在“帖子详细信息”方法中,用户对象充满了无效的值。如果我不使用编辑器模板,则用户对象将填充正确的数据。因此,编辑器模板必须有问题,但无法弄清楚它是什么。建议?

有帮助吗?

解决方案

我会重新构造一点 - 将您的LabElTextBoxValidation编辑器更改为HTML助手,然后为您的数据模型制作一个EditorteMplate。这样您就可以做这样的事情:

<% using (Html.BeginForm("Details", "User", FormMethod.Post))
{%>
  <fieldset>
   <legend>Userinfo</legend>
   <% Html.EditorFor(m => m); %>
  </fieldset>
  <input type="submit" id="btnChange" value="Change" />
<% } %>

而且您的编辑模板将是:

<%= Html.ValidatedTextBoxFor(m => m.Name); %>
<%= Html.ValidatedTextBoxFor(m => m.Email); %>
<%= Html.ValidatedTextBoxFor(m => m.Telephone); %>

在验证的情况下,您是您的新HTML助手。为此,这很容易:

public static MvcHtmlString ValidatedTextBoxFor<T>(this HtmlHelper helper, Expression thingy)
{
     // Some pseudo code, Visual Studio isn't in front of me right now
     return helper.LabelFor(thingy) + helper.TextBoxFor(thingy) + helper.ValidationMessageFor(thingy);
}

我相信这应该设置表单字段的名称,因为这似乎是问题的根源。

编辑: :这是应该为您提供帮助的代码:

public static MvcHtmlString ValidatedTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
    return MvcHtmlString.Create(
           html.LabelFor(expression).ToString() +
           html.TextBoxFor(expression).ToString() +
           html.ValidationMessageFor(expression).ToString()
           );
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top