Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将LINQ查询值传递给跨多个视图屏幕共享的视图布局_C#_Asp.net Mvc - Fatal编程技术网

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

C# 将LINQ查询值传递给跨多个视图屏幕共享的视图布局,c#,asp.net-mvc,C#,Asp.net Mvc,我使用的sharedLayout页面跨越了我所有的asp.net页面,我希望在每个视图的顶部显示登录用户的“Hello FirstName LastName”。为了得到这个结果,我正在查询我的数据库并返回一个linq对象。如何将此对象传递给视图,因为它是我所有视图页面上的共享布局,如下所示 @{ ViewBag.Title = "Begin"; Layout = "~/Views/Shared/sharedLayout.cshtml"; } 这是在我的每个查看页面的顶部,在我的sharedLa

我使用的sharedLayout页面跨越了我所有的asp.net页面,我希望在每个视图的顶部显示登录用户的“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>

我想在这里使用linq对象的名字/姓氏
我知道如何从控制器返回视图(linqobjecthere)将其传递到视图中,但由于此视图是共享的,如何将其传递到布局视图而不是当前显示的视图中。

使用@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);
}
然后使用视图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>
@model UserInfo
@Model.FirstName@Model.LastName
在共享布局中,调用
@{Html.RenderAction(“UserInfo”,“ControllerName”)}


请注意,
RenderAction()
需要在
@{}
中调用。还有一个
Html.Action()
没有此要求。据我所知,
RenderAction
更快,因为它直接写入
响应

您可以创建基本控制器并定义视图。谢谢您的帮助,完美:)