Col*_*lin 5 c# asp.net-mvc editortemplates asp.net-mvc-2
我有一个控制器有两个简单的方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
然后有一个简单的视图来显示细节:
<% 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" />
<% } %>
Run Code Online (Sandbox Code Playgroud)
如您所见,我使用编辑器模板"LabelTextBoxValidation":
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%= Html.Label("") %>
<%= Html.TextBox(Model,Model)%>
<%= Html.ValidationMessage("")%>
Run Code Online (Sandbox Code Playgroud)
显示用户信息没问题.该视图呈现完美的用户详细信息.当我提交表单时,对象用户将丢失.我调试了行"return View(User);" 在Post Details方法中,用户对象填充了可空值.如果我不使用编辑器模板,则用户对象将填充正确的数据.因此编辑器模板必定存在问题,但无法弄清楚它是什么.建议?
我会稍微重新架构一下 - 将您的 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" />
<% } %>
Run Code Online (Sandbox Code Playgroud)
您的编辑器模板将类似于:
<%= Html.ValidatedTextBoxFor(m => m.Name); %>
<%= Html.ValidatedTextBoxFor(m => m.Email); %>
<%= Html.ValidatedTextBoxFor(m => m.Telephone); %>
Run Code Online (Sandbox Code Playgroud)
其中 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);
}
Run Code Online (Sandbox Code Playgroud)
我相信这应该正确设置表单字段的名称,因为这似乎是问题的根源。
编辑:这是可以帮助您的代码:
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()
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1081 次 |
| 最近记录: |