C#MVC模式VS viewbag [英] c# mvc model vs viewbag

查看:553
本文介绍了C#MVC模式VS viewbag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有人物A的列表与人B的一个页面的列表。而这两个是分开的班L2S,再presenting两个不同的表。因此,如下您无法通过单一的模式:

Suppose you have a list of People A and a list of People B in a page. And these two are seperate classes in L2S, representing two different tables. Therefore, you cannot pass a single model as follows:

...
@model PeopleA
...
@foreach(var peopleA in Model.People) ...

@foreach(var peopleB in //what?)

因此​​,我想,我有三种选择跟随。

Accordingly, I guess, I have three options to follow.


  • 第一种方法是将页面devide为部分观点,这样我可以通过的RenderAction 助手的典范。由于我将使用这些局部视图只有一次这个选项似乎并没有吸引我。

  • 第二个选择是使用我不希望因为我preFER强类型的模型ViewBags。

  • 最后一个,最后,我正要使用,但想在这样做之前要问,就是要创建一个模型如下:

  • The first one is to devide the page into partial views so that I can pass a model through RenderAction helper. Since I will use these partial views only once this option does not seem attracting to me.
  • The second option would be to use ViewBags which I don't want to since I prefer strongly typed models.
  • The last one, finally, which I was about to use but wanted to ask before doing so, is to create a model as the following:

ModelMyPage.cs

ModelMyPage.cs

public List<PeopleA> peopleA { get; set; }
public List<PeopleB> peopleB { get; set; }

MyController.cs

MyController.cs

... 
ModelMyPage m = new ModelMyPage();
m.peopleA = // query
m.peopleB = // another query
return(m);

和你有这个想法。这是为了完成我的任务有效的方式还是有一个更好的C#的方法做我想要什么?

And you got the idea. Is this the valid way to accomplish my task or is there a better c# way to do what I want?

推荐答案

创建视图模型特定的页面,你的选择是3路我会做到这一点。

Creating a ViewModel specific to the page, as your option 3 is the way I would do it.

我相信这也是推荐的方法。

I believe this is also the recommended approach.

这篇关于C#MVC模式VS viewbag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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