Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data into a partial view or layout using MVC

Tags:

asp.net-mvc

I want to display information about the logged in user (username, company name, number of notifications, etc) in the layout and/or partial views. These will be common on every page. Is there a trick for getting this data to them, or is it a case of extending each model to have this information in them?

like image 669
Paul Deen Avatar asked Jul 18 '12 09:07

Paul Deen


People also ask

How do you pass model data to partial view?

To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.

How we can call partial view in MVC?

To create a partial view, right click on the Shared folder -> click Add -> click View.. to open the Add View popup, as shown below. You can create a partial view in any View folder. However, it is recommended to create all your partial views in the Shared folder so that they can be used in multiple views.

Can we use layout in partial view?

Partial views shouldn't be used to maintain common layout elements. Common layout elements should be specified in _Layout. cshtml files. Don't use a partial view where complex rendering logic or code execution is required to render the markup.

What is difference between layout and partial view in MVC?

A layout is something that we can include once in a single page and we can use the same layout to any number of pages. A partial view is something that we can include the same content any number of times in a single page(where it is required) and can be used in any number of pages.


1 Answers

I would suggest you can go for a child action and invoke it from the layout, By this way you can avoid carry out the information in all the view models.

Ex.

Child action

public class UserController
{
  [ChildActionOnly]
  public PartialViewResult UserInfo()
  {
     var userInfo = .. get the user information from session or db

     return PartialView(userInfo);
  }
}

Partial View

@model UserInfoModel

@Html.DisplayFor(m => m.UserName)
@Html.DisplayFor(m => m.CompanyName)
...

Layout view

<header>
  @Html.Action("UserInfo", "User")
</header>
like image 169
VJAI Avatar answered Nov 01 '22 09:11

VJAI