Message()
[get] action, I enter some text in the text area and click on Save to post the formMessage()
[post] action saves the changes, resets the value of SomeText to empty string and returns to the view.At this point I expect the text area to be empty because I have set ViewData["SomeText"]
to 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>
The reset() method resets the values of all elements in a form (same as clicking the Reset button). Tip: Use the submit() method to submit the form.
To clear an input field after submitting:Add a click event listener to a button. When the button is clicked, set the input field's value to an empty string. Setting the field's value to an empty string resets the input.
You may use JavaScript form reset() method or loop throw all textboxes and set Text property to empty string.
The problem is that your ModelState is re-filled with the posted values.
What you can do is clear it on the Action that has the Post attribute :
ModelState.Clear();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With