Asp.Net MVC Non-duplicate forms when editing / adding

When we have everything that requires user input (for example, adding a product to the database), the edit screen looks the same as the add screen. When using MVC.Net, how do you deal with this? Are you returning the same point of view? Just adjust the model to reflect the changes?

+3
source share
4 answers

Same (partial) view

You create only one, but strongly typed view (depending on the user interface, this can, of course, be a partial view). When adding new data, return this view from the controller action with the default instance of the model object (usually this is just a new instance without any properties), but when you edit, return it with the instance of the object you want to edit.

Control part

As for controller actions, you can have four of them:

  • Add GET
    return View("SomeView", new Customer());
  • Add POST
  • Change GET
    return View("SomeView", new CustomerRepository().GetCustomer(id));
  • Change POST

Bot GET actions return the same view, but with a different model, as described previously. POST actions store the submitted data, but return everything they need. Probably some RedirectToAction()...

+3

,

return View("ViewName")
+2

You can have form fields in a partial view and have two separate views using the same partial view, one message for the edit controller action method and the other location in the add controller action method.

+1
source

Partial representations are used to eliminate duplicity. You can read an example of this in the Nerd Dinner Tutorial .

+1
source

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


All Articles