为我的数据创建一个MVC ViewModels [英] Creating a MVC ViewModels for my data

查看:54
本文介绍了为我的数据创建一个MVC ViewModels的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对MVC还是很陌生,因此我对MVC视图模型的理解是正确的.它们本质上是将直接与视图交互的模型,而常规模型可能会也可能不会与视图交互.所以我有两个类UserModel和ArticleModel.显示所有用户信息的最佳方法是什么,再加上其中一篇文章的说明,我将为此创建视图模型吗?我是否只是创建一个视图模型来返回UserModel和ArticleModel的实例,还是有更好的方法?

Im still new to this MVC thing so is my understanding correct in terms of MVC View Models. They are essentially models that will interact directly with the view, where as a regular model may or may not interact with the view. So I have two classes UserModel, and ArticleModel. What is the best way to display all the user information, plus the Description of one of the Articles would I create a view model for this? Do I just create a a viewmodel that returns an instance of UserModel and ArticleModel or is there a better way?

我当前的课程:

public class UserModel
{
    public int UserId { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public DateTime CreatedDate { get; set; }
}

public class ArticleModel
{
    public int ArticleId { get; set; }
    public String Title { get; set; }
    public String Description { get; set; }
    public DateTime AddDate { get; set; }
}

推荐答案

您似乎有正确的主意.通常,您将需要将视图模型传递给视图,尤其是在这种情况下,您需要来自两个或多个实体模型的数据.在该站点上,我们经常看到人们发送一个实体模型,然后通过ViewBag或ViewData发送一些其他数据,不可避免地,解决他们问题的方法是使用视图模型.

You seem to have the right idea. Generally you will want to pass a view model to your view, especially in a case like this where you need data from two or more entity models. Far too often on this site we see people sending an entity model and then some other data by way of a ViewBag or ViewData, and inevitably, the solution to their problem is to use a view model.

视图模型可能如下所示:

The view model may look like this:

public class ViewModel
{
    public int UserId { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public DateTime CreatedDate { get; set; }
    public String Description { get; set; }
}

此拼合的版本对于在视图模型级别而非实体模型级别添加数据注释很有用.当您可能需要在一个视图中而不是另一个视图中要求输入字段时,此方法很方便.

This flattened version is useful for adding data annotations at the view model level instead of the entity model level. Handy when you may want to require a field in one view, but not in another.

或者像这样

public class ViewModel
{
   public UserModel UserModel { get; set; }
   public String Description { get; set; }
}

可以这样做

public class ViewModel
{
   public UserModel UserModel { get; set; }
   public ArticleModel ArticleModel { get; set; }
}

但是随后您将向视图发送多余的数据,这通常会随着人们的应用范围的扩大而给人们带来麻烦

But then you would be sending superfluous data to the view which can often cause problems for folks as their app grows in scope

这篇关于为我的数据创建一个MVC ViewModels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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