Reputation: 18869
I'm a little new to MVC, so I need a little help with this.
I have this partial view:
@model MySite.Models.Account.UserProfile
<ul id="nav-user">
<li class="user-name">
@String.Format("{0} {1}", Model.FirstName, Model.LastName)
</li>
</ul>
and rendering it in my Layout file:
<nav id="main">
@Html.Partial("NavUserPartial")
</nav>
In WebForms, I would use a User Control named NavUser here, and set the logged-in data in the code behind of the user control.
How can I do that using a Partial View in MVC? Where do I set that data?
Upvotes: 1
Views: 868
Reputation: 29186
For the main view, create a viewmodel class.
public class MyViewModel
{
public UserProfile UserProfile { get; set; }
}
and use it in the partial view like so:
@model UserProfile
<ul id="nav-user">
<li class="user-name">
@String.Format("{0} {1}", Model.FirstName, Model.LastName)
</li>
</ul>
When rendering the main view, you can pass whatever you need like so:
<nav id="main">
@Html.Partial("NavUserPartial", Model.UserProfile )
</nav>
Simply tailor the code to your needs.
I use viewmodels a lot, and overall they make designing MVC views a lot easier. Certainly my views are a lot easier to maintain.
Upvotes: 4