3

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?

3 Answers 3

8

That's called a child action.

Call Html.Action(...).

Sign up to request clarification or add additional context in comments.

1 Comment

Will that generate an extra request?
2

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;
}

Comments

0

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)

1 Comment

The solution is also dependent on whether or not the content changes across views. Is the content of the partial exactly the same across all parent views?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.