I would like to use a viewmodel in MVC instead of using viewbag. Is there a way that I could create some generic viewmodel that's shared between all my controllers and then use this in my views? What kind of code would I need for this? I was thinking to maybe create something in a base controller. Is that possible?
Asp.net-mvc – How to create a generic view model in MVC
asp.net-mvcasp.net-mvc-3asp.net-mvc-4
Related Topic
- Asp.net-mvc – How to render an ASP.NET MVC view as a string
- Asp.net-mvc – How to properly handle 404 in ASP.NET MVC
- Asp.net-mvc – ViewModel Best Practices
- Asp.net-mvc – Using Html.ActionLink to call action on different controller
- Asp.net-mvc – ASP.NET MVC – Set custom IIdentity or IPrincipal
- Asp.net-mvc – How to set ViewBag properties for all Views without using a base class for Controllers
- Asp.net-mvc – How to use knockout.js with ASP.NET MVC ViewModels
Best Answer
I believe the predominate method for passing data between controllers and views is to create a class that represents the data you want to pass to your view and pass that model variable to the view method.
/Models/Home/IndexViewModel.cs
Controllers/HomeController.cs
/Views/Home/Index.cshtml (in Razor MVC3)
Let's take this simple example, and build towards your specific request. The easy way would be to allow every view simply use the
MyClass
model. However, this becomes very inflexible, so here is what I would do to keep the design flexible. I'm going to assume there is some data you want to pass to many views (some or all).Create class that represents the data you want to pass to multiple views:
/Models/SharedData.cs
Create an interface for models to require a SharedData class.
/Models/ISharedDataViewModel.cs
Update the Home IndexViewModel to use the interface and shareddata
/Models/Home/IndexViewModel.cshtml
Create a Partial view that knows how to display shared data
/Views/Shared/SharedDataView.cs (in Razor MVC3)
Update the Home Index page to call the Partial view
/Views/Home/Index.cshtml (in Razor MVC3)
Now any page can call for the partial view if the pages model implements
ISharedDataViewModel
.