Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBoxFor Helper retains previous value even when model value is empty

I have an MVC form for adding a simple entity. I am using TextBoxFor(model => model.FieldName) to create the input fields. I have a Save button and a Save and New button. The Save and New button is supposed to post back to the Save action and then return the current View with an empty model to enable the user to add another entity. However, what happens is that, even though the model is indeed empty, the input fields are being generated with the values entered for the previous entity. Hope this makes sense.

I know I could do a redirect, but that seems like an ugly workaround, so if anyone has run into this before, I'd really appreciate some input.

Thanks.

like image 475
sydneyos Avatar asked Jun 02 '11 23:06

sydneyos


2 Answers

The issue here is that your ViewData.ModelState is still populated with the values from the original post, even if the Model is null and you don't explicitly pass any values into your view.

I actually don't think redirecting to the original action is that ugly of a solution, but if you don't want to do that then clearing out the ViewData should work for you:

[HttpPost]
public ActionResult Save(TestModel model)
{            
    ViewData = null;
    return View();
}
like image 143
ataddeini Avatar answered Jan 01 '23 23:01

ataddeini


I would suggest using

ModelState.Clear();

instead of

ViewData = null;

since I find that much more clear what you are trying to do. Although both will accomplish what you're trying to do.

like image 20
RickardN Avatar answered Jan 01 '23 23:01

RickardN