表单提交后重置textarea的值 [英] Reset the value of textarea after form submission

查看:46
本文介绍了表单提交后重置textarea的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我想通过转至/MyController/Message/3 向 userID=3 发送消息
  2. 这将执行 Message() [get] 操作,我在文本区域输入一些文本,然后单击保存以发布表单
  3. Message() [post] 动作保存更改,将 SomeText 的值重置为空字符串并返回视图.
  1. I want to send a message to userID=3 by going to /MyController/Message/3
  2. This executes Message() [get] action, I enter some text in the text area and click on Save to post the form
  3. Message() [post] action saves the changes, resets the value of SomeText to empty string and returns to the view.

此时我希望文本区域为空,因为我已将 ViewData["SomeText"] 设置为 string.Empty.

At this point I expect the text area to be empty because I have set ViewData["SomeText"] to 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] 操作也可以设置临时状态消息,如下所示:

The problem is the HtmlHelper is retrieving the ModelState value, which is filled with the posted data. Rather than hacking round this by resetting the ModelState, why not redirect back to the [get] action. The [post] action could also set a temporary status message like this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Message(int ID, string SomeText)
{
  // save Text to database
  SaveToDB(ID, SomeText);

  TempData["message"] = "Message sent";
  return RedirectToAction("Message");
}

在我看来,这更像是正确的行为.

This seems to me like more correct behaviour.

这篇关于表单提交后重置textarea的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆