Hi @长生猫 ,
You could use session to transfer data from content page to layout page. Please refer the following steps:
- Configure session state Add a call to
AddSession
in ConfigureServices
Add a call toUseSession
in Configure. - Configure the
Add a call toAddHttpContextAccessor()
in the ConfigureServices: to accessHttpContext
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?}"); }); }
- 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(); }
- Accesss the Session value in the Layout Page: Add the following code in the head:
Add the following code in the body:@using Microsoft.AspNetCore.Http @inject IHttpContextAccessor HttpContextAccessor
@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.
[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