简体   繁体   English

初始化部分视图的数据

[英]Initializing data for a partial view

I'm a little new to MVC, so I need a little help with this. 我对MVC有点新意,所以我需要一些帮助。

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. 在WebForms中,我将在此处使用名为NavUser的用户控件,并在用户控件后面的代码中设置登录数据。

How can I do that using a Partial View in MVC? 我如何使用MVC中的部分视图来做到这一点? Where do I set that data? 我在哪里设置这些数据?

For the main view, create a viewmodel class. 对于主视图,创建一个viewmodel类。

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. 我经常使用viewmodels,总体而言,它们使MVC视图的设计变得更加容易。 Certainly my views are a lot easier to maintain. 当然,我的观点更容易维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM