Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear fields after success

Tags:

asp.net-mvc

I have a page with 2 input type=text..

@model MVC3.ViewModel.TalkToUsVM

@using (Html.BeginForm())
{
    <ul>
        <li>@Html.TextBoxFor(m => m.TalkToUsRequest.Name)</li>
        <li>@Html.TextBoxFor(m => m.TalkToUsRequest.Email)</li>
    </ul>

    <input type="submit" value="Save"/>
}

in my controller I do this:

[HttpPost]
public ActionResult Create(TalkToUsRequest talkToUsRequest)
{
    var vm = new TalkToUsVM();

    if (TryValidateModel(talkToUsRequest))
    {
        vm.Result = "Success";

        return View("Create",vm);
    }

    vm = new TalkToUsVM
    {
        Result = "Errrooooooor",
        TalkToUsRequest = talkToUsRequest
    };

    return View(vm);
}

so the problem.. when my model is valid, I set the result to "Success" and in this point vm.TalkToUsRequest is null.. but when page is rendered, all fields are with the same value that when I submited.. even I setting vm.TalkToUsRequest = null!! How can I clear this fields?

like image 775
MuriloKunze Avatar asked Jun 01 '12 17:06

MuriloKunze


People also ask

How do I reset a form after successful submit?

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 I empty a form field 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.


2 Answers

So in this scenario you have to clear your model state if you return back to the same view. Try following:

    ModelState.Clear();     return View(vm); } 
like image 150
Lav Avatar answered Oct 05 '22 14:10

Lav


Your answer :

TryUpdateModel(yourmodelname);

and it will update your view state

and if you also want to clear all Modelstate.error at the same time you can also use :

 ModelState.Clear(); 
like image 32
abhijeet abanave Avatar answered Oct 05 '22 13:10

abhijeet abanave