在MVC中将值从Controller传输到Shared View

Alm*_*lma 5 asp.net-mvc asp.net-mvc-4

我需要从控制器发送一些值到共享视图以显示在顶部

    [HttpPost]
    [Route("login")]
    public async Task<ActionResult> Login(LogInRequest logInRequest)
    {
        IEnumerable<UserClaim> UserClaims = null;
        User user = null;
        if (ModelState.IsValid)
        {
      user = await GetUserByEmailAndPassword(logInRequest.UserName, logInRequest.Password);
            if (user.Id != 0)
            {
                 showMenu = await ShowLoanMenu(logInRequest);
                if (showMenu)
                {
        ******** I need to send showMenu and user.Name to shared view
             return RedirectToAction(Constants.Views.SearchView, Constants.Views.LoanDriverController);
                }
            }
               .....
              return View(logInRequest);
    }
Run Code Online (Sandbox Code Playgroud)

我不想使用TempData,viewdata,viewbag或session,我如何通过查询字符串或添加到模型来发送它.

这是布局之一:

      <ul>
            <li class="logo">
                <img src="~/Content/Images/logo.png" alt="" />
            </li>
            <li class="nav-item">
                  ***  @if(showmenu is true)
                 {
                    <ul>
                        @Html.ActionLink("Loan Driver", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                    </ul>
                }
            </li>
        </ul>
Run Code Online (Sandbox Code Playgroud)

这是另一种布局:

 <div class="header">
       <div class="master-container">
        <div class="heading">Garage</div>
        <div class="primary-nav">
            <ul>
                <li>******show name of the person</li>
                <li>@Html.ActionLink("Logout", "logout", "Home")</li>
               </ul>
           </div>
        </div>
Run Code Online (Sandbox Code Playgroud)

Cag*_*lan 1

我想您希望这个用于当前请求,而不是所有请求,因此接受的答案不是正确的方法。要在单个请求范围内与视图或子控制器共享数据,最简单的方法是将数据放入 HttpContext.Items。这是在同一请求期间由所有视图和子控制器共享的。

HttpContext.Items["UIOptions"] = new UIOptions { ShowMenu = true }; 
Run Code Online (Sandbox Code Playgroud)

您可以使用扩展来抽象它:

public static class HttpContextExtensions
    {
        public static UIOptions GetUIOptions(this HttpContext httpContext)
        {
            var options = httpContext.Items["UIOptions"] ?? (object) new UIOptions();
            httpContext.Items["UIOptions"] = options;
            return options;
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中,设置选项

HttpContext.GetUIOptions().ShowMenu= true
Run Code Online (Sandbox Code Playgroud)

在你看来,像这样访问它:

ViewContext.HttpContext.GetUIOptions()
Run Code Online (Sandbox Code Playgroud)

我通常会进一步抽象它,以便您使用以下属性来配置它

[UIOptions(ShowMenu=true)]
public ActionResult MyAction()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

因此,您编写一个 ActionFilter,它检查操作的属性,并在 ActionExecuting 阶段使用属性属性设置 httpContext.GetUIOptions() 对象的属性。