【发布时间】:2021-06-09 18:28:30
【问题描述】:
我希望能够控制当用户导航回表单时表单是否保留其值。举个例子。
- 用户在 /transfertaxes/create 页面上成功提交表单
- 用户导航到 /transfertaxes/index
- 用户使用浏览器后退按钮导航回 /transfertaxes/create
我目前观察到的行为是保留表单值。我尝试过以多种方式禁用缓存,但都没有奏效。这如何实现?
Startup.cs
namespace LoanCalculator
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddDbContext<LoanCalculatorContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("LoanCalculatorContext")));
}
// 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("/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();
//ADDED THIS
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = context =>
{
context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
context.Context.Response.Headers.Add("Expires", "-1");
}
});
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
创建.cshtml.cs
namespace LoanCalculator.Pages.TransferTaxes
{
public class CreateModel : PageModel
{
private readonly LoanCalculator.Data.LoanCalculatorContext _context;
public CreateModel(LoanCalculator.Data.LoanCalculatorContext context)
{
_context = context;
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public TransferTax TransferTax { get; set; }
// To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.TransferTax.Add(TransferTax);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}
_Layout.cshtml
...
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<title>@ViewData["Title"] - LoanCalculator</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css?v0000000002" />
</head>
...
【问题讨论】:
-
嗨@MaxPowers,我的回答是否帮助您解决了您的问题?如果可以,请您接受作为答案吗?如果没有,请您跟进让我知道吗?参考:How to accept as answer .谢谢。
标签: asp.net-core .net-core entity-framework-core razor-pages