How to Clear model after submit the data in databa

2019-04-01 11:28发布

问题:

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);
}

回答1:

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.



回答2:

in very simplest way try it

if(ModelState.IsValid)

{

//code here to save data to database

db.SaveChanges();

ModelState.Clear();

}

return view(new CategoryViewModel());


回答3:

Hear is what does ModelState.Clear()

ModelState.Clear() is used to clear errors but it is also used to force the MVC engine to rebuild the model to be passed to your View.

So as in your case @Vsevolod Goloviznin suggested you can use:

return View(new CategoryViewModel());

to have view with empty values