Search code examples
c#asp.net-mvchistory.js

Working with mvc partial view and history.js


I'm using history js, https://github.com/browserstate/history.js/ to and Mvc Partial view, here is my code

In Partial Home

<a id="CreateUser" class="btn btn-primary">Create User </a>

and in my @section scripts to push new url and load partial content in 'state change event'

$('#back').click(function (e) {
    History.pushState({ state: 1 }, "Create User", "/System/User/Create/");
});

in contoller there is also logic to load partial view if its ajax call and full view if not, this is to protect from user if they press refresh when in ~/System/User/Create/. any way my script onClick script in section doesnt work user in /System/User called from Partial View or Ajax, I can solve this by attaching OnClick Event inside outside @section scripts so it became like this:

<a id="CreateUser" class="btn btn-primary">Create User </a>
<script>
        $('#back').click(function (e) {
           History.pushState({ state: 1 }, "Create User", "/System/User/Create/");
        });
</script>

@section scripts
{
<script>
    $('#back').click(function (e) {
           History.pushState({ state: 1 }, "Create User", "/System/User/Create/");
    });
</script>
}

but this is redundant and pain to maintain I know this happend because @section doesnt work with Ajax/Partial, anyway is there's cleaner alternative other than this.


Solution

  • Nevermind findout that '.click' need to be rebind after loading ajax, but with .on('click' there is no need to rebind event handler, so I now just need script on click event in global js.