应该如何发布的数据在MVC为蓝本? [英] How should posted data be modeled in MVC?

查看:82
本文介绍了应该如何发布的数据在MVC为蓝本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我得到的视图模型的想法 MVC 但是,这样做的更新和删除的时候,似乎像有应该张贴到控制器的独特模式。我注意到默认剃刀控制器使用 ViewBag 持有Selectlists。

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.

我想这是回程的视图模型(域实体真的)可重复使用的,因为它被剥离不必要的数据。但它似乎是诉诸 ViewBag 使用视图模型的时候,因为视图模型可以包含无厘头的选择列表 S和这样的。

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.

所以我的问题是什么样的模式是有制作不同的发布的数据模式? (接到埃斯波西托的MVC 2本书这个词),以及如何应发布的数据模型进行相关的视图模型?例如,好像我会尝试,包括与视图模型发布的数据模型。我是新来的 MVC 而不是从网​​络的形式来背景无论是。我真的想了解的最佳模式为将要发送到控制器的数据建模。

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.

推荐答案

我经常使用相同的视图模型为它传递到编辑/更新视图和POST操作接收它。下面是常用的方式:

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

至于域模型和视图模型之间的映射是担心我会建议您 AutoMapper

这篇关于应该如何发布的数据在MVC为蓝本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆