【问题标题】:Form retains values when navigating back导航返回时表单保留值
【发布时间】:2021-06-09 18:28:30
【问题描述】:

我希望能够控制当用户导航回表单时表单是否保留其值。举个例子。

  1. 用户在 /transfertaxes/create 页面上成功提交表单
  2. 用户导航到 /transfertaxes/index
  3. 用户使用浏览器后退按钮导航回 /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


【解决方案1】:

浏览器实现后向缓存 (BFCache)。当您点击返回按钮时,实际页面不会重新加载,脚本也不会重新运行。

如果您必须清除表单以防用户点击返回按钮,您可以收听“pageshow”事件,执行以下操作:

window.addEventListener("pageshow", () => {
  // update hidden input field
});

请注意,reset() 不适用于隐藏的输入字段。 见this

【讨论】:

    【解决方案2】:

    您可以绑定到window.onbeforeunload 以防止浏览器完全缓存页面。将以下代码添加到您的_Layout.cshtml:

    <script>
        window.onbeforeunload = function () {
            $('form')[0].reset();
        };
    </script>
    

    结果:

    参考:

    https://stackoverflow.com/a/14548415/11398810

    【讨论】:

      猜你喜欢
      • 2016-12-25
      • 1970-01-01
      • 2020-12-18
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 2018-09-23
      • 2012-02-09
      相关资源
      最近更新 更多