Search code examples
c#asp.netasp.net-mvcrazorback-button

Back button causes current page postback. ASP.Net MVC


I have a controller with 'Details' action and 'Edit' action. I navigate to Edit using View(); then a page with a partial view is rendered.

In the partial view there is a form:

@using (Html.BeginForm("CreateOrEdit", "Licenses", FormMethod.Post, new { @class = "pure-form pure-form-aligned", id = "change", onsubmit = "process(this);" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div class="floatLeft width100per">
        @Html.HiddenFor(model => model.Id)
        @Html.HiddenFor(model => model.CustomerId)

        <button onclick="goBack()" type="button" class="pure-button pure-button-primary newButton">Back</button>
        <input type="submit" value="Save" class="pure-button pure-button-primary newButton marginRight10" onclick="getModules(); setGuid('@Guid.NewGuid()');" />
        <div class="floatLeft pure-form">

goBack() function:

function goBack() {
    history.go(-1);
}

If I navigate to Edit and press the back button, everything's fine. But if I press the Save button, form is being submitted and CreateAndEdit action is called - still OK.

The CreateAndEdit action uses:

RedirectToAction("Details", new { id = license.Id });

in order to navigate to Details page again.

Then, if I go to "Edit" again and then press Back - CreateAndEdit action is called again - Not OK!

How can I always go back to "Details" page without calling CreateAndEdit when Back is pressed.


Solution

  • You need to disable the cache for the page you don't want a user to be able to go back to due to form submission, etc.

    You could try decorating the route with

    [OutputCache(NoStore=true, Duration=0)]
    

    I believe [NoCache] will also work as a decoration on your controller action.