Need advice on how to structure asp mvc razor page
- Now I wonder will I get something if I refactor my code so each section which data comes from database will be partial view?
- On this page I need about 20 value objects to display all needed data.
I have made one "ViewModel" class that contains all data I need and set that viewModel class as razor page 开发者_Go百科model. Is this the right way how I should do this or there is some smarter way?
public class MyViewModelClass{
public ValueObjectx x;
public ValueObjecty y;
public ValueObjectz z;
public List<ValueObjectT> tList;
public List<ValueObjectG> gList;
public List<ValueObjectS> sList;
}
In a scenario like this I would typically have each section as a partial view. Each section is responsible for it's own layout and ViewModel. This prevents the tendency to have a super view which has to know about too many things in order to render.
I would not use one ViewModel for all the data. I would only use the ViewModel for the data that might actually be posted back to the server. For all the other data, like lists, I would put it on the ViewBag
. Like:
public ViewResult SomeAction()
{
var model = GetYourModelData();
ViewBag.TList = GetTList();
ViewBag.GList = GetGList();
ViewBag.SList = SList();
return View(model);
}
You could put all the lists in a separate helper object if you use them a lot.
Note that this is not a "this is how you should do it answer", it is more a description of what works for me. But as I see it the model of the view is one thing and the actual data, as data in drop downs etc., on the view is another thing and should be put in the ViewData
property, but the ViewBag
is just a dynamic wrapper around the ViewData
property. You can then use the properties on the ViewBag
as input to your partial views that should make up each of your sections.
精彩评论