Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset the value of textarea after form submission

  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.

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> 
like image 307
xraminx Avatar asked Apr 25 '09 00:04

xraminx


People also ask

How do I reset form values after submitting?

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.

How do I clear text area after submitting?

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.

How do you clear fields after form submit in asp net c#?

You may use JavaScript form reset() method or loop throw all textboxes and set Text property to empty string.


1 Answers

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(); 
like image 78
Olivier Payen Avatar answered Oct 10 '22 01:10

Olivier Payen