简体   繁体   中英

How can I load the first page of an MVC 4 application via AJAX?

How can I load the first page of an MVC 4 application via AJAX?

I already have the structure set-up to load all the subsequent pages, but I've just hit a brick wall.

After adding the history management through history.js, I've changed my partial views to have a back button - which works as expected.

My problem is that after navigating to a couple of pages and then pressing the Back button, when I get to the first item on the windows history - ie: the index.chtml page - this page loads with the navigation bar appearing twice. After pressing F5, the page loads correctly.

What I'm doing wrong and what is the best way to fix this?

Thanks in advance for your help

By the way, this is the JavaScript I'm loading on the Layout View:

$(function () {

var contentShell = $('#bodyContent');

var History = window.History, State = History.getState();

$(".ajaxLink").on('click', function (e) {        
    e.preventDefault();
    var url = $(this).data('href');
    var title = $(this).data('title');
    History.pushState(null, title, url);
});

History.Adapter.bind(window, 'statechange', function () {
    State = History.getState();       
    navigateToURL(State.url);
});

function navigateToURL(url) {        
    $.ajax({
        type: "GET",
        url: url,
        dataType: "html",
        success: function (data, status, xhr) {
            contentShell.html(data);
        },
        error: function (xhr, status, error) {
            alert("Error loading Page.");
        }
    });
}   

$('.history-back').on('click', function (e) {        
       e.preventDefault();
       History.back();
       return false;
})   
});

This looks for me like a known problem, bug related to the click events which are fired twice in some browsers. This behavior is causing the History.pushState(...) in your code to execute twice.

You can try to add sth. like e.stopPropagation() to your code after. More on that problem you can find here: https://stackoverflow.com/a/21511818/2270888

Try something like this in your "first item" controller action:

public ActionResult Index()
{
   if (Request.IsAjaxRequest())
   {
       return PartialView();
   }

   return View();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM