将LINQ查询值传递给跨多个视图屏幕共享的视图布局

本文关键字:视图 屏幕共享 布局 查询 LINQ 值传 | 更新日期: 2023-09-27 18:09:33

我使用的是横跨我所有的asp.net页面的sharedLayout页面,我想在每个视图的顶部登录的用户的"Hello FirstName LastName"。为了得到这个,我正在查询我的数据库并返回一个linq对象。我如何将这个对象传递给视图,因为它是我所有视图页面的共享布局。

@{
ViewBag.Title = "Begin";
Layout = "~/Views/Shared/sharedLayout.cshtml";
}

这是在我的每个视图页面的顶部,在我的sharedLayout页面,我有以下部分显示用户名/姓

<div class="nav-bar">
            <a href="@Url.Action("Index", "Home")"><img src="~/Images/logo.png" id="logo" /></a>
            <img src="~/Images/testpicture.png" id="userpic" />
            <span id="user">I want the first name/lastname here from a linq object</span>
        </div>

我知道如何将其传递给控制器return View(linqobjecthere)的视图,但由于此视图是共享的,我如何将其传递给布局视图,而不是当前显示的视图。

将LINQ查询值传递给跨多个视图屏幕共享的视图布局

使用@Html.RenderAction()

设置一个返回所需数据的控制器动作:

// ChildActionOnly attribute makes sure that
// the action cannot be called directly from the url
[ChildActionOnly] 
public ActionResult UserInfo() {
    // Get the data you need
    var userInfo = (Linq to get userInfo);
    return PartialView("UserInfo", userInfo);
}

然后用view html:

创建一个名为"UserInfo"的强类型局部视图
@model UserInfo
<div class="nav-bar">
    <a href="@Url.Action("Index", "Home")">
        <img src="~/Images/logo.png" id="logo" />
    </a>
    <img src="@Model.UserPicHref" id="userpic" />
    <span id="user">@Model.FirstName @Model.LastName</span>
</div>

在共享布局中,调用@{Html.RenderAction("UserInfo", "ControllerName")}

注意RenderAction()需要在@{ }中调用。还有一个Html.Action()没有这个要求。从我听说RenderAction更快,因为它直接写入Response