ASP.NET MVC Editortemplateモデルは、投稿後に失われます
-
02-10-2019 - |
質問
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);
}
次に、詳細を表示するための簡単なビューが1つあります。
<% 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("")%>
ユーザー情報を表示することは問題ありません。ビューは完全にユーザーの詳細をレンダリングします。フォームを送信すると、オブジェクトユーザーが紛失します。私は行で「return View(user);」でデバッグされました。 Postの詳細方法では、ユーザーオブジェクトはNullable値で満たされています。エディターテンプレートを使用しない場合、ユーザーオブジェクトは正しいデータで満たされています。したがって、エディターテンプレートに何か問題がある必要がありますが、それが何であるかを理解することはできません。提案?
解決
私は少し再びアーカイトします - あなたのラベルTextBoxValidationエディターをHTMLヘルパーに変更し、次にデータモデルの1つの編集を作成します。そうすれば、このようなことができます。
<% 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()
);
}
所属していません StackOverflow