I've a Razor view with lots of graph and other text fields which gets data from controller. I'm thinking of passing a ViewModel
from controller to the view which then will parse the relevant content and display it.
Could anyone suggest if above approach is the best practice to solve such, in MVC?
The ViewModel
class may look like below:
public class ViewModelDemo
{
public MyChart chart {get;set;}
public string LeftContent {get;set}
public string bottomContent {get;set;}
public ChartLeged legent {get;set}
......
}
public class MyChart
{
public List<int> xAxis {get;set}
public List<int> yAxis {get;set;}
......
}
Reason I'm trying to return ViewModel
is that there are may parts of the page which have different data.
Absolutely. A ViewModel is a perfectly acceptable solution to this problem. See Section 12.1.5 of Palermo's excellent MVC in Action book (conveniently in the free sample)
The other option is to create a separate view model type for our views from the domain model. We’ll create a specialized class, just for that one view. We can shape that type however we like, and allow the view to shape our view model however we want. The advantage of a separated view model is that our views won’t influence the domain model in any way. For less complex applications, this separation is not necessary and overcomplicates the design. As complexity of the views increases, the design of the views has more and more impact on our domain model, unless the view model and domain model are separated.
http://www.manning.com/palermo/Samplechapter12.pdf
I think you solution is corret.
Another approach could be to split up the big razor view into smaller partial views, each with a simpler view model. This is usefull for readability, separation of responsability, ecc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With