TryUpdateModel,ASP .NET MVC 3的实证 [英] Real example of TryUpdateModel, ASP .NET MVC 3

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

问题描述

我不明白,怎么用TryUpdateModel并保存MVC架构在同一时间。

I can't understand, how to use TryUpdateModel and save the MVC architecture at the same time.

如果我没有记错,与datacontexts工作必须在模型中。所以,这样的code

If I am not mistaken, work with datacontexts must be in the Model. So, such code

var db=new TestEverybody();//it is class, which was generated by EntityFramework 
var currentTesting=db.Testing.(t => t.id == id).First();

必须位于模式,而不是在控制器,一定不是吗?

must be situated in the Model, not in the Controller, mustn't it?

但TryUpdateModel使用的ussual例子是以下内容:

But the ussual examples of TryUpdateModel usage is following:

    public ActionResult Edit(Testing obj)//Testing collection
    {
        var db = new TestEverybody();
        var currentTesting=db.Testing.(t => t.id == obj.id).First();
        TryUpdateModel(currentTesting);
        db.SaveChanges();            
        return RedirectToAction("Index");
    }

不这样打破了MVC架构?我们在控制器数据库的工作,而不是在特殊的Model类。

Doesn't this way break the MVC architecture? We work with database in the controller, not in the special Model class.

那么,什么是真正的项目中使用TryUpdateModel的最佳方式?

So, what is the best way to use TryUpdateModel in a real project?

推荐答案

由于OP问,这里的视图模型模式的例子,或者我喜欢叫它 - ASP.NET MVC得当

Since the OP asked, here's an example of the ViewModel pattern, or as I like to call it - ASP.NET MVC done properly.

那么,为什么使用视图具体型号

So why use a view specific model


  1. 您应该只将信息传递给你的看法,它需要。

  2. 通常情况下,你需要添加额外的视图的元数据(如标题/描述属性)。这些不属于你的实体。

  3. 使用TryUpdateModel /的UpdateModel是错误的。不要使用(我会解释为什么)。

  4. 这是非常罕见的,您的视图模型将完全匹配您的实体。人们往往最终增加额外的克鲁夫特他们的实体或(不到哪去)只使用ViewBag而不是强类型的视图模型属性。

  5. 如果您使用的是ORM可以运行与延迟加载的属性(N + 1)的问题。您的观点不应该发出查询。

我们会用一个简单的实体启动:

We'll start with a simple entity:

public class Product {
    public int Id {get;set;}
    public string Name {get;set;}
    public string Description {get;set;}
    public decimal Price {get;set;}
}

和假设你有一个简单的表格,用户可以在更新名称说明的产品。但是,你正在使用(非常贪婪)TryUpdateModel。

And let's say you have a simple form where the user can only update the Name and Description of the product. But you're using (the very greedy) TryUpdateModel.

于是我就用任意数量的工具(如小提琴手)来构造一个POST自己并发送以下内容:

So I use any number of tools (like Fiddler) to construct a POST myself and send the following:

名称= WhatverIWant&安培;简介= UnluckyFool&安培;价格= 0

Name=WhatverIWant&Description=UnluckyFool&Price=0

嘛ASP.NET MVC模型绑定是要检查输入表单收集,看到你的实体存在,这些属性和自动绑定它们。所以,当你调用TryUpdateModel在你刚刚从数据库中检索实体,所有匹配属性将被更新(包括价格!)。时间到了新的选择。

Well the ASP.NET MVC model binder is going to inspect the input form collection, see that these properties exist on your entity and automatically bind them for you. So when you call "TryUpdateModel" on the entity you've just retrieved from your database, all of the matching properties will be updated (including the Price!). Time for a new option.

public class EditProductViewModel {
    [HiddenInput]
    public Guid Id {get;set;}

    [Required]
    [DisplayName("Product Name")]
    public string Name {get;set;}

    [AllowHtml]
    [DataType(DataType.MultilineText)]
    public string Description {get;set;}
}

这仅包含我们需要在我们查看属性。请注意,我们还增加了一些验证属性,显示属性和一些MVC特定的属性。

This contains just the properties we need in our view. Notice we've also added some validation attributes, display attributes and some mvc specific attributes.

由于没有什么,我们有我们的视图模型它可以使你的观点更清洁的限制。例如,我们可以通过在我们看来下面呈现出我们整个编辑表单:

By not being restricted in what we have in our view model it can make your views much cleaner. For example, we could render out our entire edit form by having the following in our view:

@Html.EditorFor(model => model)

会的mvc检查所有我们已经添加到我们的视图模型和自动这些属性线了验证,标签和正确的输入字段(即用于描述一个textarea)。

Mvc will inspect all of those attributes we've added to our view model and automatically wire up validation, labels and the correct input fields (i.e. a textarea for description).

[HttpPost]
public ActionResult EditProduct(EditProductViewModel model) {

    var product = repository.GetById(model.Id);

    if (product == null) {
        return HttpNotFound();
    }

    // input validation
    if (ModelState.IsValid) {

        // map the properties we **actually** want to update
        product.Name = model.Name;
        product.Description = model.Description;

        repository.Save(product);

        return RedirectToAction("index");
    }

    return View(model)
}

这是一个从这个code做什么的相当明显。我们没有任何不良影响,当我们更新我们的实体,因为我们明确地对我们的实体设置属性。

It's fairly obvious from this code what it does. We don't have any undesirable effects when we update our entity since we are explicitly setting properties on our entity.

我希望这足够你想用它解释了视图模型模式。

I hope this explains the View-Model pattern enough for you to want to use it.

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

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