在ASP.NET使用视图模型MVC 3 [英] Using view models in ASP.NET MVC 3

查看:98
本文介绍了在ASP.NET使用视图模型MVC 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是比较新的车型查看和我正在与他们使用的一些问题。这里有一个情况,我想知道最好的做法是什么...

I'm relatively new to view models and I'm running into a few problems with using them. Here's one situation where I'm wondering what the best practice is...

我把所有的视图需要到视图模型的信息。下面是一个例子 - 请原谅任何错误,这是codeD了我的头顶部

I'm putting all the information a view needs into the view model. Here's an example -- please forgive any errors, this is coded off the top of my head.

public ActionResult Edit(int id)
{
    var project = ProjectService.GetProject(id);

    if (project == null)
        // Something about not found, possibly a redirect to 404.

    var model = new ProjectEdit();
    model.MapFrom(project); // Extension method using AutoMapper.

    return View(model);
}

如果屏幕上只允许一个或两个字段,编辑在视图模型回来它缺少相当多的数据(因为它应该是)。

If the screen only allows editing of one or two fields, when the view model comes back it's missing quite a bit of data (as it should be).

[HttpPost]
public ActionResult Edit(int id, ProjectEdit model)
{
    var project = ProjectService.GetProject(id);

    if (project == null)
        // Something about not found, possibly a redirect to 404.

    try
    {
        if (!ModelState.IsValid)
            return View(model) // Won't work, view model is incomplete.

        model.MapTo(project); // Extension method using AutoMapper.
        ProjectService.UpdateProject(project);
        // Add a message for the user to temp data.

        return RedirectToAction("details", new { project.Id });
    }
    catch (Exception exception)
    {
        // Add a message for the user to temp data.

        return View(model) // Won't work, view model is incomplete.
    }
}

我的临时解决方案是从头开始重新创建视图模型,从领域模型重新填充它,表单数据重新申请,然后正常进行。但是这使得视图模型参数有些无意义。

My temporary solution is to recreate the view model from scratch, repopulate it from the domain model, reapply the form data to it, then proceed as normal. But this makes the view model parameter somewhat pointless.

[HttpPost]
public ActionResult Edit(int id, ProjectEdit model)
{
    var project = ProjectService.GetProject(id);

    if (project == null)
        // Something about not found, possibly a redirect to 404.

    // Recreate the view model from scratch.
    model = new ProjectEdit();
    model.MapFrom(project); // Extension method using AutoMapper.

    try
    {
        TryUpdateModel(model); // Reapply the form data.

        if (!ModelState.IsValid)
            return View(model) // View model is complete this time.

        model.MapTo(project); // Extension method using AutoMapper.
        ProjectService.UpdateProject(project);
        // Add a message for the user to temp data.

        return RedirectToAction("details", new { project.Id });
    }
    catch (Exception exception)
    {
        // Add a message for the user to temp data.

        return View(model) // View model is complete this time.
    }
}

有没有更优雅的方式?

Is there a more elegant way?

修改

这两个答案都是正确的,所以我想如果我可以奖励他们。点头去MJ然而,由于试错后,我发现他的解决方案是最瘦的。

Both answers are correct so I would award them both if I could. The nod goes to MJ however since after trial and error I find his solution to be the leanest.

我仍然能够使用助手也一样,吉米。如果我加入我需要的东西显示给视图袋(或视图的数据),像这样......

I'm still able to use the helpers too, Jimmy. If I add what I need to be displayed to the view bag (or view data), like so...

ViewBag.Project= project;

然后我可以做以下...

I can then do the following...

@Html.LabelFor(model => ((Project)ViewData["Project"]).Name)
@Html.DisplayFor(model => ((Project)ViewData["Project"]).Name)

一个黑客一点,它需要的领域模型与 System.ComponentModel.DisplayNameAttribute 在某些情况下的装饰,但我已经做到这一点。

A bit of a hack, and it requires the domain model to be decorated with System.ComponentModel.DisplayNameAttribute in some cases, but I already do that.

我很想打电话给...

I'd love to call...

@Html.LabelFor(model => ViewBag.Project.Name)

但动态导致前pressions一个问题。

But dynamic causes a problem in expressions.

推荐答案

在一些试验和错误(又名code,然后恨它)的学习,我目前preferred做法是:

After some trial-and-error (aka code it, then hate it) learning, my currently preferred approach is:

我使用视图模型的只有的绑定输入字段。所以你的情况,如果你的视图只编辑两个字段,那么你的视图模型只会有两个属性。对于填充视图所需要的数据(下拉列表,标签等),我用的是动态ViewBag。

I use view-models only to bind input fields. So in your case, if your view is only editing two fields, then your view-model will only have two properties. For the data required to populate the view (drop-down lists, labels, etc), I use the dynamic ViewBag.

我相信,显示视图(即填充任何视图需要显示),并捕获提交的表单值(绑定验证等等)是两个单独的担忧。而且我发现,混合填充是从视图调回与该视图所需的数据变得混乱,并准确往往不是造成你的情况。我不喜欢正在传递部分填充的对象。

I believe that displaying the view (i.e. populating anything the view needs to display), and capturing the posted form values (binding, validation, etc) are two separate concerns. And I find that mixing the data required to populate the view with that which is posted back from the view gets messy, and creates exactly your situation more often than not. I dislike partially populated objects being passed around.

我不知道如何发挥出来与Automapper(用于映射域对象的动态ViewBag)虽然,因为我还没有使用过它。我相信它有可能工作DynamicMap方法?你不应该有任何问题,自动映射张贴的强类型视图模型到域对象。

I’m not sure how this plays out with Automapper (for mapping the domain object to the dynamic ViewBag) though, as I haven’t used it. I believe it has a DynamicMap method that may work? You shouldn’t have any issues auto-mapping the posted strongly-typed ViewModel onto the Domain object.

这篇关于在ASP.NET使用视图模型MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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