简体   繁体   English

MVC ASP.NET中的ViewData和ViewModel

[英]ViewData and ViewModel in MVC ASP.NET

I'm new to .Net development, and now are following NerdDinner tutorial. 我是.Net开发的新手,现在正在关注NerdDinner教程。 Just wondering if any of you would be able to tell me 只是想知道你们中是否有人能告诉我

What is the differences between ViewData and ViewModel ViewData和ViewModel之间有什么区别

(all I know is they are used to pass some form of data from controller to view) and perhaps tell me on what situation should I use ViewData instead of ViewModel and vice versa (我所知道的是他们习惯于将某些形式的数据从控制器传递到视图)并且可能告诉我应该在什么情况下使用ViewData而不是ViewModel,反之亦然

Thanks in advance! 提前致谢!

Sally 出击

What is ViewData ? 什么是ViewData?

  • dictionary object that you put data into, which then becomes available to the view. 您将数据放入的字典对象,然后可供视图使用。

ViewData Sample ViewData示例

Controller Action method likes : Controller Action方法喜欢:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var featuredProduct = new Product
        {
            Name = "Smart Phone",
            QtyOnHand = 12
        };

        ViewData["FeaturedProduct"] = featuredProduct;
        return View();
    }
}

How to use ViewData on View ? 如何在View上使用ViewData?

@{    
    var viewDataProduct = ViewData["FeaturedProduct"] as Product;
 }
<div>
    Today's Featured Product is!
    <h3>@viewDataProduct.Name</h3>
</div>

What is a ViewModel ? 什么是ViewModel?

  • Allow you to shape multiple entities from one or more data models or sources into a single object 允许您将一个或多个数据模型或源中的多个实体整形为单个对象
  • Optimized for consumption and rendering by the view 针对视图的消费和渲染进行了优化

Its like : 就像是 :

查看模型图像

How to use ViewModel with MVC 3 ? 如何将ViewModel与MVC 3一起使用?

Domain Model 领域模型

public class Product
    {
        public Product() { Id = Guid.NewGuid(); Created = DateTime.Now; }
        public Guid Id { get; set; }
        public string ProductName { get; set; }
    }

ViewModel 视图模型

public class ProductViewModel
    {
        public Guid VmId { get; set; }

        [Required(ErrorMessage = "required")]
        public string ProductName { get; set; }

    }

Controller Action Method 控制器动作方法

[HttpGet]
public ActionResult AddProduct()
{
    //for initialize viewmodel
    var productViewModel = new ProductViewModel();

    //assign values for viewmodel
    productViewModel.ProductName = "Smart Phone";

    //send viewmodel into UI (View)
    return View("AddProduct", productViewModel);
}

View - AddProduct.cshtml 查看 - AddProduct.cshtml

@model YourProject.ViewModels.ProductViewModel //set your viewmodel here

Conclusion 结论

  • By using ViewModel can pass strongly-typed data into View 通过使用ViewModel可以将强类型数据传递给View
  • But ViewData is Loosely Typed.So Need to cast data on View 但是ViewData是松散类型的。所以需要在View上投射数据
  • ViewModel can use for Complex scenarios such as merging more than one domain model ViewModel可用于复杂方案,例如合并多个域模型
  • But ViewData can be used only for simple scenarios like bring data for the drop down list 但ViewData只能用于简单的场景,例如为下拉列表带来数据
  • ViewModel can use for attribute-based validation scenarios which needed for Ui ViewModel可用于Ui所需的基于属性的验证方案
  • But Cannot use ViewData for such kind of validations 但是不能使用ViewData进行这种验证
  • As a best practices always try to use strongly typed data with Views.ViewModel is the best candidate for that. 作为最佳实践,总是尝试使用Views.ViewModel的强类型数据。

ViewData: ViewData的:

In short, use ViewData as support data, such as a datasource to a SelectList. 简而言之,使用ViewData作为支持数据,例如SelectList的数据源。

ViewModel: 视图模型:

ASP.NET MVC ViewModel Pattern ASP.NET MVC ViewModel模式

When a Controller class decides to render an HTML response back to a client, it is responsible for explicitly passing to the view template all of the data needed to render the response. 当Controller类决定将HTML响应呈现给客户端时,它负责显式传递给视图模板呈现响应所需的所有数据。 View templates should never perform any data retrieval or application logic – and should instead limit themselves to only have rendering code that is driven off of the model/data passed to it by the controller. 视图模板永远不应该执行任何数据检索或应用程序逻辑 - 而应该将自己限制为仅具有由控制器传递给它的模型/数据驱动的渲染代码。

[...] [...]

When using [the "ViewModel"] pattern we create strongly-typed classes that are optimized for our specific view scenarios, and which expose properties for the dynamic values/content needed by our view templates. 当使用[ViewModel]模式时,我们创建强类型类,这些类针对我们的特定视图场景进行了优化,并公开了视图模板所需的动态值/内容的属性。 Our controller classes can then populate and pass these view-optimized classes to our view template to use. 然后,我们的控制器类可以填充这些视图优化类并将其传递给我们的视图模板以供使用。 This enables type-safety, compile-time checking, and editor intellisense within view templates. 这样可以在视图模板中实现类型安全,编译时检查和编辑器智能感知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM