Controller for ASP.NET MVC Partial Views

I recently started building a website with ASP.NET MVC 4 and I am trying to wrap my head around how it works.

There is some data that I would like to display on each page and realized that Partial Views are great for this.

Is it possible to create a controller that always provides data for a partial view? Or how can I solve this?

+3


source to share


3 answers


This is called a child activity.



Challenge Html.Action(...)

.

+8


source


You can create a controller action for partial view. But if you are looking for nesting something on every page, you should consider adding it to the _Layout.cshtml page

You can create a normal action method that 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 the name " PartialUserInfo

" present in your folder Views/Users

(Assuming your controller name is Users. If you want to specify a view that is in a different location, you can mention it when you call the view method



returnView("Partial/UserInfo",objVm);

      

This will return a View called "UserInfo" in your folder Views/Users/Partial

.

in your partial view you can disable the normal layout (if you have one), doint this

@model UserViewModel 
@{
  Layout=null;
}

      

+2


source


One way is to have a model for the parent view (one of which contains all the partial parts) that contains the models for the partial views as properties in its model

Example:

MainModel.ModelForPArtialView1
MainModel.ModelForPArtialView2
MainModel.ModelForPArtialView3

      

This way you can do it in the parent view

@Html.Partial("PartialView1",MainModel.ModelForPArtialView1)
@Html.Partial("PartialView2",MainModel.ModelForPArtialView2)
@Html.Partial("PartialView3",MainModel.ModelForPArtialView3)

      

0


source







All Articles