How to simulate data in MVC?

I think I get the idea of ViewModel in MVC , but when performing updates and deletes, it seems like there should be a great model to send to the controller. I noticed that razor controllers use the ViewBag by default to select Selectlists.

I assume that makes the ViewModel (domain entities really) reusable in the return path, because it is devoid of unnecessary data. But it seems that using ViewBag does not make sense when using view models, since the view model may contain Selectlist , etc.

So my question is, what patterns exist to create separate β€œhosted data” models? (received this term from the book Esposito MVC 2). And how should relate to a data model based on view models? For example, it seems that I will try to include published data models in the view models. I am new to MVC and not from web-forms background. I would really like to understand the best samples for modeling the data that will be sent to the controller.

0
source share
1 answer

Often I use the same view model to pass it to the Edit / Update view and get it in the POST action. A template is commonly used here:

 public ActionResult Edit(int id) { DomainModel model = ... fetch the domain model given the id ViewModel vm = ... map the domain model to a view model return View(vm); } [HttpPost] public ActionResult Edit(ViewModel vm) { if (!ModelState.IsValid) { // there were validation errors => redisplay the view // if you are using dropdownlists because only the selected // value is sent in the POST request you might need to // repopulate the property of your view model which contains // the select list items return View(vm); } DomainModel model = ... map the view model back to a domain model // TODO: process the domain model return RedirectToAction("Success") } 

Regarding the mapping between the domain model and view models, I would recommend AutoMapper to you.

+2
source

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


All Articles