gpt4 book ai didi

c# - Post 后 Asp.Net MVC EditorTemplate 模型丢失

转载 作者:太空狗 更新时间:2023-10-29 23:48:40 26 4
gpt4 key购买 nike

我有一个带有两个简单方法的 Controller :

用户 Controller 方法:

[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);
}

然后有一个用于显示详细信息的简单 View :

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

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

最佳答案

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

关于c# - Post 后 Asp.Net MVC EditorTemplate 模型丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2737432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com