0

I am using asp.net core razor engine. After I enter text in my TextArea and hit the submit button I want to clear the text in the TexArea. I have not been able to find anything on how to do this using html or c#. Here is my code for the TextAreaFor

 <h1>Add Your Comment</h1>
                @using(Html.BeginForm("AddComment","Home"))
                {
                    <p>
                        <label>Your Comment</label>
                        @Html.TextAreaFor(d=>d.comment)
                        @Html.ValidationMessageFor(d => d.comment)
                    </p>

                    <input type="submit" name="submit" value="Add my Comment!"/>
                }

Here is my controller for AddComment

[HttpPost]
        [Route("addComment")]
        public IActionResult AddComment(Messages model)
        {  
            var user_id = HttpContext.Session.GetString("Id");
            if(user_id == null){
                return RedirectToAction("Index");
            }
            model.Users_id = Convert.ToInt32(user_id.ToString());
            userFactory.addComment(model, user_id);
            setTempData();

            ViewBag.Messages = userFactory.FindAll();
            model.comment ="";
            return View("Login", model);  
        }

The calls for userFactory work, it is a call to my factory that talks to my db

Aaron
  • 4,380
  • 19
  • 85
  • 141
  • Only with JavaScript, I'm afraid: `document.getElementById("formId").addEventListener("submit", function() { this.innerText = ""; })`, something like that. – DontVoteMeDown Jan 06 '17 at 19:08
  • What do you do after you submit? Handle the response in a controller action? What are you trying to achieve? – Arve Systad Jan 06 '17 at 19:10
  • You should expand your post a little with more detail, or more code. I guess your entire application is more than this snippet. – Arve Systad Jan 06 '17 at 19:15
  • @ArveSystad, I added my controller method. The code sends the user input to my db. I am trying to figure out is there is a way to clear the data in the textareas after that data has been submitted to the db – Aaron Jan 06 '17 at 19:31
  • 1
    Do not return the view. Follow the PRG pattern and redirect back to the GET method that generates the view. Refer [this answer](http://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111) for an explanation of the behavior. –  Jan 07 '17 at 06:35

1 Answers1

0

After all the work is done, you should not return View(...), but rather redirect the user to it with RedirectToAction . By doing that, you clear out all form fields, and make use of the Post-redirect-get pattern, which stops your users from double-submitting.

The same pattern should nearly always be applied when you post an entire page.

Arve Systad
  • 5,471
  • 1
  • 32
  • 58