Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Clear model after submit the data in database in MVC3

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);
}
like image 554
Mukesh Kumar Avatar asked Dec 21 '14 11:12

Mukesh Kumar


People also ask

How do you clear model values?

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.

How to clear Fields after Form submit in ASP net c#?

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 "".

How do you clear fields after form submit in ASP NET MVC?

The Form Fields which are created using Model class are cleared by clearing the Model using ModelState. Clear function. int personId = person.

How do you clear form data after submit in asp net core?

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.


1 Answers

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.

like image 130
Vsevolod Goloviznin Avatar answered Nov 15 '22 12:11

Vsevolod Goloviznin