Reputation: 6656
I've just recently started to build a web site using ASP.NET - MVC 4, and Im trying to wrap my head around how this works.
There are some data I would like to display on every page and have understood that Partial Views are great for this.
Is it possible to create a controller that always provides data for the partial view? Or how can I solve this?
Upvotes: 3
Views: 6199
Reputation: 39248
One way is to have a model for the parent view (the one hosting all the partials) that contains the models for the partial views as properties on its model
EX:
MainModel.ModelForPArtialView1
MainModel.ModelForPArtialView2
MainModel.ModelForPArtialView3
That way you can do this on the parent view
@Html.Partial("PartialView1",MainModel.ModelForPArtialView1)
@Html.Partial("PartialView2",MainModel.ModelForPArtialView2)
@Html.Partial("PartialView3",MainModel.ModelForPArtialView3)
Upvotes: 0
Reputation: 218722
You can create a controller action for the partial view. But if you are looking for inlcluding some thing on every page, you should think about adding that to your _Layout.cshtml page
You can create a normal action method which returns a partial view like this
public ActionResult UserInfo()
{
UserViewModel objVm=GetUserInf();
// do some stuff
return View("PartialUserInfo",objVM);
}
This will return a view with name "PartialUserInfo
" present in your Views/Users
folder( Assuming your controller name is Users. If you want to specify a view which is a different location you can mention it when calling the View method
returnView("Partial/UserInfo",objVm);
This will return a View called "UserInfo" in your Views/Users/Partial
folder.
in your partial view, you can disable the normal layout( if you have one) by doint this
@model UserViewModel
@{
Layout=null;
}
Upvotes: 2