How should posted data be modeled in MVC?

元气小坏坏 提交于 2019-12-25 17:19:34

问题


I think I get the idea of the ViewModel in MVC but, when doing updates and deletes, it seems like there should be a distinct model for posting to the controller. I noticed the default razor controllers use ViewBag to hold Selectlists.

I guess that makes the ViewModel (domain entities really) reusable on the return trip because it is stripped of unnecessary data. But it seems like resorting to ViewBag doesn't make sense when using view models because the view model can contain the Selectlists and such.

So my question is what kinds of patterns are there for making distinct "posted data" models? (got this term from Esposito's MVC 2 book) And how should the posted data model be related to the view models? For example, it seems like I will try including the posted data models with the view models. I'm new to MVC and not coming from a web-forms background either. I would really like to understand the best patterns for modeling the data that will be sent to the controller.


回答1:


Often I use the same view model for passing it to the Edit/Update view and receiving it in the POST action. Here's the commonly used pattern:

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

As far as the mapping between the domain model and view models is concerned I would recommend you AutoMapper.



来源:https://stackoverflow.com/questions/6844058/how-should-posted-data-be-modeled-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!