Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

asp.net mvc - c# mvc model vs viewbag

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.

  • 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...