【问题标题】:Asp.Net MVC EditorTemplate Model is lost after Post发布后 Asp.Net MVC EditorTemplate 模型丢失
【发布时间】:2011-02-13 19:28:31
【问题描述】:

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

用户控制器方法:

[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("")%>

显示用户信息没问题。该视图完美地呈现了用户详细信息。 当我提交表单时,对象用户丢失了。我在“返回视图(用户)”行上进行了调试;在 Post Details 方法中,用户对象填充了可为空的值。如果我不使用编辑器模板,用户对象将填充正确的数据。所以编辑器模板一定有问题,但无法弄清楚它是什么。有什么建议吗?

【问题讨论】:

  • 使用 Firebug 或 Fiddler 比较两种情况下提交的表单。它会有所不同。修复它。

标签: c# asp.net-mvc asp.net-mvc-2 editortemplates


【解决方案1】:

我会稍微重新架构一下 - 将您的 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); %>

其中 ValidatedTextBoxFor 是您的新 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()
           );
}

【讨论】:

  • Html.EditorFor(m => m) 行渲染模型的所有成员,这不是我想要的。我只想渲染用户类的三个成员。但是新的 html 助手看起来不错,谢谢! :)
  • 如果您在 \Views\\EditorTemplates\ 中定义自己的 EditorTemplate 则不会
  • Tejs:要做到这一点,这将相当容易:您能否更清楚地了解如何创建这样的 HtmlHelper?我正在尝试使用这种结构创建一个,但我没有这样做。
  • 好的,给我几分钟,我会用代码发布一个新的答案。
  • 改为 m); %> 你应该使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 2012-01-15
  • 1970-01-01
  • 2015-06-22
  • 2012-05-14
相关资源
最近更新 更多