Asp.Net MVC - empty model does not return empty data

I have a form that a user can fill out x times with the data they want. The form is submitted for the next action.

[HttpPost] public ActionResult Manage(ProductOptionModel DataToAdd) { if (!ModelState.IsValid) { return View(DataToAdd); } var ProdServ = new ProductService(); if (DataToAdd.ID != 0) { //Edit Mode. DataToAdd = ProdServ.EditProductOption(DataToAdd); ViewData["Message"] = "Option Changes Made"; }else { //Add DataToAdd = ProdServ.AddProductOption(DataToAdd); ViewData["Message"] = "New Option Added"; } var RetModel = new ProductOptionModel() {ProductID = DataToAdd.ProductID}; return View(RetModel); } 

So, below, I shade the model (leaving only the required field), and then return to the view. However, the view contains data from a previously submitted form.

Any ideas why? I debugged the code and checked that the RetModel variable is empty.

+4
source share
2 answers

Html helpers work this way when the view returns to the HTTP POST. They prefer to publish data on model values.

Use Post / Redirect / Get

That's why I suggest you use the Post / Redirect / Get pattern, which is very well supported in Asp.net MVC. Your controller actions should be redirected to some GET action after the POST completes successfully, as in your case.

 public ActionResult Process() { return View(new Data { Id = -1 }); } [HttpPost] public ActionResult Process(Data data) { if (!this.ModelState.IsValid) { return View(data); } new MyService().ProcessData(data); return RedirectToAction("Process"); } 

And if you display all the previously entered data, you can provide them in a GET action or transfer them from POST to GET using the TempData dictionary.

+5
source

This is because the input helper assembly will first check the published data and use these values ​​if they exist. Then he will look at the model.

0
source

Source: https://habr.com/ru/post/1311614/


All Articles