在表单提交后重置文本区域的值

时间:2022-11-12 12:38:41
  1. I want to send a message to userID=3 by going to /MyController/Message/3
  2. 我想发送一条消息到userID=3,通过访问/MyController/ message /3。
  3. This executes Message() [get] action, I enter some text in the text area and click on Save to post the form
  4. 这将执行消息()[get]操作,我在文本区域中输入一些文本,然后单击Save以发布表单。
  5. Message() [post] action saves the changes, resets the value of SomeText to empty string and returns to the view.
  6. 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?

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

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>

9 个解决方案

#1


39  

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正在检索模型状态值,该值包含已发布的数据。与其通过重新设置模型状态来绕过它,为什么不重定向回[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.

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

#2


68  

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属性的动作上清除它:

ModelState.Clear();

#3


7  

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

#4


1  

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.

希望这个有帮助。

#5


1  

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"),如果您愿意的话。或者在没有htmlhelper扩展的情况下呈现输入。它们被设计为从ModelState获取值,而不是从模型(或viewdata)获取值。

#6


0  

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.

(您将在其中一个load事件上执行此操作。

<body onload="...">

Hope this helps.

希望这个有帮助。

#7


0  

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

我相当确定文本区域正在从请求中获取值。由于ViewData["SomeText"]是空的,所以在面板下面形成。

#8


0  

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 code from 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, useViewData should be false, attemptedValue should be false unless an error has been set in the model state.

由于您显式地为ViewData提供了一个值,因此useViewData应该是false,调度值应该是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);

#9


0  

Do s.th. like this:

做s.th。是这样的:

add:

添加:

ModelState.Clear();

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

在提交按钮的返回语句之前,操作方法。为我工作。它可能对你有用。

#1


39  

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正在检索模型状态值,该值包含已发布的数据。与其通过重新设置模型状态来绕过它,为什么不重定向回[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.

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

#2


68  

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属性的动作上清除它:

ModelState.Clear();

#3


7  

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

#4


1  

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.

希望这个有帮助。

#5


1  

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"),如果您愿意的话。或者在没有htmlhelper扩展的情况下呈现输入。它们被设计为从ModelState获取值,而不是从模型(或viewdata)获取值。

#6


0  

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.

(您将在其中一个load事件上执行此操作。

<body onload="...">

Hope this helps.

希望这个有帮助。

#7


0  

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

我相当确定文本区域正在从请求中获取值。由于ViewData["SomeText"]是空的,所以在面板下面形成。

#8


0  

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 code from 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, useViewData should be false, attemptedValue should be false unless an error has been set in the model state.

由于您显式地为ViewData提供了一个值,因此useViewData应该是false,调度值应该是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);

#9


0  

Do s.th. like this:

做s.th。是这样的:

add:

添加:

ModelState.Clear();

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

在提交按钮的返回语句之前,操作方法。为我工作。它可能对你有用。