开发者

How to clear fields after post back in asp.net mvc?

I am wondering how do I clear fields after a postback in asp.net mvc? Like right now 开发者_如何学运维when validation errors occur the fields stay populated with whatever a user would entered. This is fine however, when no validation errors occur I want the all the fields to clear and a message to display.

So right now I have the success displaying by using ViewData but not sure how to get the fields to clear.


Try this:

if(ModelState.IsValid)
{
    ModelState.Clear();
}
return View();


Phil Haack said:

Try calling

ModelState["value1"].Value = new
ValueProviderResult(null,
string.Empty,
CultureInfo.InvariantCulture);

before you return the view from within your controller action.

What this does is keep all the errors associated with the key "value1", but replaces the value with an empty value.

From this SO question


Sounds like a job for the PRG (Post Redirect Get) pattern because you don't want the users to refresh the page and have it submit again.

To do this I would put a message or flag in your TempData so that you can inspect that when you redirect back to the original url to then display a message to the user.


You can assign the model, new reference when you post back you model in the view.
Something like this.

    if (ModelState.IsValid)
    {
        //Do your stuff here. 

        yourModel = new Moodel();
        return View(yourModel);

    }

In this scenario all model fields will be empty and nothing will be displayed at form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜