I am submitting some data in database and after submit I want to show same page. But I am viewing the page the textbox value is not empty.
ModelState.Clear();
I have used to clear the textbox.
But still the textbox value is remain. please suggest me to clear the model after submit in mvc3.
public ActionResult AddNewCategory(CategoryViewModel model) {
if (ModelState.IsValid) {
int result = 0;
var categoryEntity = new Category {
CategoryName = model.CategoryName, CategorySlug = model.CategorySlug
};
result = Convert.ToInt32(_categoryRepository.AddNewCategory(categoryEntity));
if (result > 0) {
ModelState.Clear();
}
}
return View(model);
}
If you are getting your Model from a form and you want to manipulate the data that came from the client form and write it back to a view, you need to call ModelState. Clear() to clean the ModelState values.
You may use JavaScript form reset() method or loop throw all textboxes and set Text property to empty string. Show activity on this post. Show activity on this post. This code will collect all textboxes in a list and set their textproperty to "".
The Form Fields which are created using Model class are cleared by clearing the Model using ModelState. Clear function. int personId = person.
One way would be to call Response. Redirect("[YourPageName]. aspx") after you have submitted everything. Another alternative would be to add a method that clears out your form like below.
You're getting the same model, because you're passing it to the view View(model)
. You have couple options here: either pass an empty model, or redirect to the get variant of your post action.
1)
if (ModelState.IsValid)
{
//saving
if (result > 0)
{
ModelState.Clear();
return View(new CategoryViewModel());
}
}
2)
if (ModelState.IsValid)
{
//saving
if (result > 0)
{
return RedirectToAction("AddNewCategory");
}
}
PS: I strongly advice to use the second approach as you might want to make other DB calls to construct your model and you won't want to do this in multiple places.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With