如何创建Asp.Net MVC 3视图模型 [英] How to create Asp.Net MVC 3 view model

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

问题描述

我有一个使用Entity框架连接到的数据库。我的家庭视图由许多部分视图组成,显示应用程序的不同部分。在我的控制器中,我想发送一个包含所有这些不同实体数据对象的模型到我的视图,然后将所需的信息发送到我的特定部分视图。我相信我需要一个视图模型,但从来没有这样做过。让我总结一下我的目标:
我有四个表:currentFav,TopTenFav,流派和歌曲
我已经创建了一个查询功能的存储库类,如查找所有歌曲,添加歌曲等。
我的索引视图分为局部视图,如当前的fav,前十和类型。



我的问题是如何从控制器发送我的模型对我的看法,然后从那里到我所有的部分观点,任何人都有想法? thx

解决方案

我如何设计您的ViewModel是为每个Partial视图创建一个Interface,以便:

 接口IPartialView1 //正确命名它
{
currentFav CurrentFav {get; }
}

然后在您的实际ViewModel:

  class HomeViewModel:IPartialView1,IPartialView2,... 
{
currentFav CurrentFav {get;组; }
}

根据您的看法,以及部分视图填充您的HomeViewModel: / p>

 <! -  CurrentFav-Partial.cshtml  - > 
@Model IPartialView1

< span> @ model.CurrentFav.color< / span>

这允许您创建要传入视图的任何模型,只要它有每个Partials的接口都需要渲染它们。每个ViewModel可以通过Interfaces为您创建的任何类型的视图包含任意数量的其他模型/类。


I have a database through which I connect to by using Entity framework. My Home View consists of many partial views that display different parts of the application. In my controller i would like to send a model containing all those different Entity data objects to my view, and then send the needed info to my particular partial views. I believe I need a view model for this but have never done this before. Let me summarize my objective: I have four tables: currentFav,TopTenFav,Genres, and Songs I have created a repository class with some query functions such as find all the songs, add a song and so on. My index view is divided into partial views such as current fav, top ten, and genres.

My question is how would I send my model from the controller to my view and then from there to all of my partial views, anyone got an idea? thx

解决方案

How I would design your ViewModel is to create an Interface for each of your Partial views such that:

interface IPartialView1  //Name it appropriately
{
   currentFav CurrentFav { get; }
}

Then on your actual ViewModel:

class HomeViewModel : IPartialView1, IPartialView2,....
{
   currentFav CurrentFav { get; set; }
}

Populate your HomeViewModel as you see fit, and in your partial views:

<!-- CurrentFav-Partial.cshtml -->
@Model IPartialView1

<span>@model.CurrentFav.color</span>

This allows you to create any Model you want to pass into the view, and as long as it has the interface each of the Partials need to render they can. Each ViewModel can contain any number of other models/classes via Interfaces for any type of view you create.

这篇关于如何创建Asp.Net MVC 3视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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