0

I would like to be able to control whether or not a form retains it's values when the user navigates back to it. Take the following example.

  1. User successfully submits form on page /transfertaxes/create
  2. User is navigated to /transfertaxes/index
  3. User uses browser back button to navigate back to /transfertaxes/create

The behavior I am currently observing is the form values are retained. I have tried disabling caching in several ways, none of which have worked. How can this be accomplished?

Chrome enter image description here

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();
            });
        }
    }
}

Create.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>
...
Rena
  • 30,832
  • 6
  • 37
  • 72
MaxPowers
  • 474
  • 1
  • 4
  • 18

2 Answers2

0

Browsers implement back-forward cache (BFCache). When you hit back button the actual page is not reloaded and scripts doesn't rerun.

If you have to clear your form in case user hit back button, you can listen to "pageshow" event do something like the following:

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

Note that reset() does not work for hidden input fields. See this

Ask
  • 3,076
  • 6
  • 30
  • 63
0

You can bind to window.onbeforeunload to prevent the browser from fully caching the page.Add the following code to your _Layout.cshtml:

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

Result:

enter image description here

Reference:

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

Rena
  • 30,832
  • 6
  • 37
  • 72