TryUpdateModel 的真实示例,ASP .NET MVC 3 [英] Real example of TryUpdateModel, ASP .NET MVC 3

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

问题描述

我无法理解,如何同时使用 TryUpdateModel 和保存 MVC 架构.

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

如果我没记错的话,使用数据上下文必须在模型中.所以,这样的代码

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 使用的常见示例如下:

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 的要求,这里是 ViewModel 模式的一个示例,或者我喜欢称之为 - 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;}
}

假设您有一个简单的表单,用户可以更新产品的NameDescription.但是您正在使用(非常贪婪的)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.

所以我使用任意数量的工具(如 Fiddler)自己构建一个 POST 并发送以下内容:

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

名称=WhatverIWant&Description=UnluckyFool&Price=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 将检查我们添加到视图模型中的所有属性,并自动连接验证、标签和正确的输入字段(即用于描述的文本区域).

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

从这段代码可以很明显地看出它的作用.我们在更新实体时没有任何不良影响,因为我们在实体上显式设置了属性.

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.

我希望这足以解释 View-Model 模式,让您想要使用它.

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

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

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