开发者

c# mvc model vs viewbag

开发者 https://www.devze.com 2023-03-18 02:13 出处:网络
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

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 peop开发者_如何学JAVAleB in //what?)

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

  • 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

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

MyController.cs

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

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?


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.


No, there is not any better idea. In asp.net MVC, M stands for ViewModels, not the Business, Domain models. It is recommended to create ViewModels for your views and it's not reccomended to use Business Models. You should design your ViewModels to fit the need of controller interactions with Domain, and from controller to view interactions


Your first and third options seem both OK.

ad 1) "only using them once" is not a good argument-against. Use Partial views to organize views.

ad 2) Use the Viewbag to add small items like a lookup list.

ad 3) ViewModels are (becoming) common in MVC. This is probably the best approach.


I would do it the third way. Additionally, if you are going to render identical html for each person in both arrays, I would concat them before foreach:

var person in Model.PeopleA.Concat(Model.PeopleB)


I usually create a Model for the page, and name it as such, eg AccountDetailsPageModel. Then other models can be properies of this for complex pages.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号