在回发后保持MVC的价值持久性

时间:2016-10-21 23:09:23

标签: asp.net-mvc model-view-controller

我需要在顶部菜单中显示用户名,我将其添加到ViewData,但在搜索页面的搜索页面中,我正在回发,数据不再存在。如何在不使用tempdata的情况下实现持久性。观看包或会议。

这是我的登录页面,显示成功登录后的搜索视图。

    [HttpPost]
    [Route("login")]
    public async Task<ActionResult> Login(LogInRequest logInRequest)
    {
           User user = null;
        if (ModelState.IsValid)
        {
            user = await GetUserByEmailAndPassword(logInRequest.UserName, logInRequest.Password);
            if (user.Id != 0)
            {
                  ViewData["Name"] = user.Name;
                  return View("~/Views/LoanDriver/Search.cshtml");
                }
                else
                {
                    return View("~/Views/LoanDriver/Dashboard.cshtml");
                }
              ......
            return View("~/Views/Home/Index.cshtml");
          }

这是我的搜索视图:

@model CarFinance.Garage.Web.Models.SearchResult

@{
Layout = "~/Views/Shared/_SecondaryPage.cshtml";
}
@using (Html.BeginForm("SearchResult", "LoanDriver", FormMethod.Post))
 {
   @Html.AntiForgeryToken()
   .......}
  @Html.Partial("~/Views/LoanDriver/SearchResult.cshtml")

这是显示顶部菜单的母版页:

@{
      Layout = "~/Views/Shared/MasterLayout.cshtml";
  }
@section header {

               @(ViewData["Name"])

它首次显示,但是当我将刷新(回发)的搜索按钮放到页面名称为空时。

1 个答案:

答案 0 :(得分:0)

我最好的方法是创建一个BaseController

所以基本上

public class BaseController : Controller
{
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Here you can run any code you like, this code will always run after any action has been executed
        ViewData["Name"] = "User Name";
        base.OnActionExecuted(filterContext);
    }
}

然后在您的控制器上,您只需继承BaseController

public class HomeController : BaseController

现在,在每个页面请求中,它将首先填充ViewData["Name"]