Share via

MVC Core 有没有更好的方法给 _Layout.cshtml 页传递数据

长生猫 1 Reputation point
Jul 4, 2021, 8:23 AM

在控制器中这样写

 public async Task< IActionResult > Index()    
{  
    ViewData["Title"] = "未命名";  
    return View();  
 }  

index.cshtml 页面中

@ViewData["Title"] 就可以得到字符 "未命名"

index.cshtml 使用 _Layout.cshtml 页

index.cshtml 可以跳转到 ProductCenter.cshtml 页

ProductCenter.cshtml 使用 _Layout.cshtml 页

public async Task< IActionResult > ProductCenter()    
 {  
       //注释   ViewData["Title"] 后 ProductCenter.cshtml  页无法得到 字符 "未命名"  
       //   ViewData["Title"] = "未命名";             
        return View();  
  }  

如果想每一个页面都可以得到 字符 "未命名" 。

那么每个IActionResult< IActionResult > 都需要有 ViewData["Title"] = "未命名";

这种方法太麻烦,有没有更简单的方法。

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,806 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 33,181 Reputation points Microsoft External Staff
    Jul 5, 2021, 2:53 AM

    Hi @长生猫 ,

    You could use session to transfer data from content page to layout page. Please refer the following steps:

    1. Configure session state Add a call to AddSession in ConfigureServices
      Add a call to UseSession in Configure.
    2. Configure the
      Add a call to AddHttpContextAccessor() in the ConfigureServices: to access HttpContext and access sesson value in the View Page. After the above configuration, the result as below:
      public void ConfigureServices(IServiceCollection services)  
      {  
          services.AddDistributedMemoryCache();  
      
          services.AddSession(options =>  
          {  
              options.Cookie.Name = ".AdventureWorks.Session";  
              options.IdleTimeout = TimeSpan.FromMinutes(10);  
              options.Cookie.HttpOnly = true;  
              options.Cookie.IsEssential = true;  
          });  
          services.AddHttpContextAccessor()  
          //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();  
          services.AddControllersWithViews();  
      }  
      
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
      {  
          if (env.IsDevelopment())  
          {  
              app.UseDeveloperExceptionPage();  
          }  
          else  
          {  
              app.UseExceptionHandler("/Home/Error");  
              // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
              app.UseHsts();  
          }  
          app.UseHttpsRedirection();  
          app.UseStaticFiles();  
      
          app.UseRouting();  
      
          app.UseAuthorization();  
          app.UseSession();  
          app.UseEndpoints(endpoints =>  
          {  
              endpoints.MapControllerRoute(  
                  name: "default",  
                  pattern: "{controller=Home}/{action=Index}/{id?}");  
          });  
      }  
      
    3. Set Session value in the Controller:
      public IActionResult Index()  
      {  
          if (string.IsNullOrEmpty(HttpContext.Session.GetString("Title")))  
          {  
              HttpContext.Session.SetString("Title", "Layout Title");  
          }  
          return View();  
      }  
      public IActionResult Privacy()  
      {  
          return View();  
      }  
      
    4. Accesss the Session value in the Layout Page: Add the following code in the head:
      @using Microsoft.AspNetCore.Http  
      @inject IHttpContextAccessor HttpContextAccessor    
      
      Add the following code in the body:
      @if (!string.IsNullOrEmpty(HttpContextAccessor.HttpContext.Session.GetString("Title")))  
      {  
          var value = HttpContextAccessor.HttpContext.Session.GetString("Title");  
          <span>@value</span>  
      }  
      

    The result as below: In the Index Action method, we set the session value, in the Privacy action method, there is no need to set session value again.

    111701-8.gif

    [Note]

    • In the above sample, we are using session to store the value, please pay more attention to the Session Expired time. More detail information, see Session state.
    • Currently in Microsoft Q&A we only support English, could you please edit your question into English? Thanks for your understanding.

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.