C# 表单提交后重置textarea的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/787895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:11:37  来源:igfitidea点击:

Reset the value of textarea after form submission

c#asp.net-mvcforms

提问by xraminx

  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.
  1. 我想通过转到 /MyController/Message/3 向 userID=3 发送消息
  2. 这将执行 Message() [get] 操作,我在文本区域输入一些文本并单击保存以发布表单
  3. Message() [post] 操作保存更改,将 SomeText 的值重置为空字符串并返回到视图。

At this point I expect the text area to be empty because I have set ViewData["SomeText"] to string.Empty

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

Why is text area value not updated to empty string after post action?

为什么在发布操作后文本区域值没有更新为空字符串?

Here are the actions:

以下是操作:

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

And the corresponding 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>

采纳答案by roryf

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:

问题是 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");
}

This seems to me like more correct behaviour.

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

回答by tvanfosson

Is it possible that the model state has been updated with an error? I believe that it will pull the attempted value from the model state rather than from view data or the model if the model state isn't valid.

模型状态是否可能已更新错误?我相信如果模型状态无效,它将从模型状态而不是从视图数据或模型中提取尝试的值。

EDIT: I'm including the relevant section of the source codefrom the TextArea HtmlHelper extension below. It appears to me that it does exactly what I expected -- if there has been a model error, it pulls the value from the model state, otherwise it uses it from ViewData. Note that in your Post method the "SomeText" key shouldn't even exist until you set it, i.e., it won't be carried forward from the version of the code that responds to the GET.

编辑:我在下面包含来自 TextArea HtmlHelper 扩展的源代码的相关部分。在我看来,它完全符合我的预期——如果出现模型错误,它会从模型状态中提取值,否则它会从 ViewData 中使用它。请注意,在您的 Post 方中,“SomeText”键在您设置它之前甚至不应该存在,即它不会从响应 GET 的代码版本中继承。

Since you explicitly supply a value to the ViewData, useViewDatashould be false, attemptedValueshould be false unless an error has been set in the model state.

由于您显式地为 ViewData 提供了一个值,因此useViewData应该为 false,attemptedValue除非在模型状态中设置了错误,否则应该为 false。

    // If there are any errors for a named field, we add the css attribute.
    ModelState modelState;
    if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState)) {
        if (modelState.Errors.Count > 0) {
            tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
        }
    }

    // The first newline is always trimmed when a TextArea is rendered, so we add an extra one
    // in case the value being rendered is something like "\r\nHello".
    // The attempted value receives precedence over the explicitly supplied value parameter.
    string attemptedValue = (string)htmlHelper.GetModelStateValue(name, typeof(string));
    tagBuilder.SetInnerText(Environment.NewLine + (attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(name) : value)));
    return tagBuilder.ToString(TagRenderMode.Normal);

回答by Jeff Ancel

That is a clientside behavior. I would recommend using javascript. If you use JQuery, you can do it like this:

这是一种客户端行为。我建议使用javascript。如果你使用 JQuery,你可以这样做:

<script type="text/javascript">
$(function(){ $("#SomeText").val("");});
</script>

I don't use Javascript anymore, but I believe in regular JS that it is like:

我不再使用 Javascript,但我相信常规的 JS 是这样的:

document.getElementById("SomeText").value = "";

(You would do this on one of the load events.

(您可以在加载之一上执行此操作。

<body onload="...">

Hope this helps.

希望这可以帮助。

回答by Mike Geise

I am fairly certain the textarea is grabbing the value from the Request.Form under the hood since ViewData["SomeText"] is empty.

由于 ViewData["SomeText"] 为空,我相当确定 textarea 正在从引擎盖下的 Request.Form 获取值。

回答by ?a?da? Tekin

The html helpers read the value from the ModelState. And there's no elegant way to override this behaviour.

html 助手从 ModelState 读取值。并且没有优雅的方来覆盖这种行为。

But if you add this line after SaveToDB(ID, SomeText), it should work :

但是如果你在 之后添加这一行SaveToDB(ID, SomeText),它应该可以工作:

ModelState["SomeText"].Value = 
    new ValueProviderResult("", "", CultureInfo.CurrentCulture);

回答by Olivier Payen

The problem is that your ModelState is re-filled with the posted values.

问题是您的 ModelState 重新填充了发布的值。

What you can do is clear it on the Action that has the Post attribute :

您可以做的是在具有 Post 属性的 Action 上清除它:

ModelState.Clear();

回答by MalachiteBR

I tried everything, but only worked when I did something like this:

我尝试了一切,但只有在我做这样的事情时才有效:

ModelState.Clear();
//This will clear the address that was submited
viewModel.Address = new Address();
viewModel.Message = "Dados salvos com sucesso!";
return View("Addresses", ReturnViewModel(viewModel));

Hope this helps.

希望这可以帮助。

回答by Kirsten

Instead of using ModelState.Clear() which clears the whole modelstate, you can do ModelState.Remove("SomeText"), if you want to. Or render the Input without the htmlhelper-extensions. They are designed to take the Value from ModelState instead of the Model (or viewdata).

如果需要,您可以执行 ModelState.Remove("SomeText") 而不是使用 ModelState.Clear() 清除整个模型状态。或者在没有 htmlhelper-extensions 的情况下呈现输入。它们旨在从 ModelState 而不是模型(或视图数据)中获取值。

回答by Kirsten

Do s.th. like this:

做某事 像这样:

add:

添加:

ModelState.Clear();

before the returnstatement of the submit buttons action method. Works for me. It could work for you.

return提交按钮操作方的声明之前。为我工作。它可以为你工作。