此时,我希望文本区域为空,因为我已将ViewData [“ SomeText”]设置为string.Empty
为什么后操作后文本区域值未更新为空字符串?
操作如下:
[AcceptVerbs(HttpVerbs.Get)] public ActionResult Message(int ID) { ViewData["ID"] = ID; return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Message(int ID, string SomeText) { // save Text to database SaveToDB(ID, SomeText); // set the value of SomeText to empty and return to view ViewData["SomeText"] = string.Empty; return View(); }
和对应的视图:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"> <% using (Html.BeginForm()) { %> <%= Html.Hidden("ID", ViewData["ID"])%> <label for="SomeText">SomeText:</label> <%= Html.TextArea("SomeText", ViewData["SomeText"]) %> <input type="submit" value="Save" /> <% } %> </asp:Content>
问题是HtmlHelper正在检索ModelState值,该值已用发布的数据填充。与其通过重置ModelState来解决这个问题,不建议将其重定向回[get]操作。[post]操作还可以设置如下临时状态消息:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Message(int ID, string SomeText) { // save Text to database SaveToDB(ID, SomeText); TempData["message"] = "Message sent"; return RedirectToAction("Message"); }
在我看来,这似乎是更正确的行为。