如何创建Asp.Net MVC 3视图模型 [英] How to create Asp.Net MVC 3 view model
问题描述
我有四个表: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屋!