HTML5 History API MVC

时间:2015-05-31 11:53:40

标签: asp.net-mvc html5 asp.net-mvc-4 html5-history

我正在创建一个MVC应用程序,页面上显示一个简单的自定义选项卡界面。当用户选择每个选项卡时,我会执行AJAX GET请求以将新内容加载到选项卡主体区域。虽然我希望实现HTML5历史记录API,以便更新浏览器历史记录,并且用户可以通过单击浏览器后退按钮返回到先前的选项卡,但这样可以正常工作。 我已经使用下面列出的核心构建了一个粗略的原型,但我仍然坚持能够返回到选项卡控件的第一个状态。 例如,当我加载页面时。选项卡一。然后,我单击选项卡二,然后单击三和四。单击浏览器后退按钮可返回选项卡三,选项卡二而不是选项卡一。

我非常感谢任何人提出的任何建议(稍后将整理代码以更多地与浏览器兼容)

<div id="publicationList">
@{Html.RenderAction("DocumentsView", "Publications", new { @area = "InformationCentre", @id = @Model.selectedCategory });}

@section scripts
{
    <script type="text/javascript">
        $(".tabOption").click(function (e) {
            e.preventDefault();
            var categoryID = $(this).attr("data-categoryID");
            GetCategoryPublications(categoryID);

            if (history.pushState) {
                history.pushState({ id: categoryID }, null, "");
            }
        });

        function GetCategoryPublications(categoryID)
        {
            $.ajax({
                type: 'GET',
                url: '@Url.Action("DocumentsView", "Publications", new { @area = "InformationCentre" })',
                async: false,
                data: { id: categoryID },
                success: function (data) {
                    $(".tabOption").removeClass("selected");
                    $('.tabOption[data-categoryID=' + categoryID + ']').addClass('selected');
                    $('#publicationList').html(data);
                }
            });
        }

        $(window).bind('popstate', function (e) {
            var state = e.originalEvent.state;
            if (state) {
                if (state.id !== undefined) {
                    GetCategoryPublications(state.id);
                }
            }
        });

    </script>
    }

1 个答案:

答案 0 :(得分:1)

我看到我现在做错了什么。 我没有在页面的初始加载上推动状态。这个&#39; replaceState&#39;:

有一个更合适的命令
if (history.replaceState) {
        history.replaceState({ id: @Model.selectedCategory }, null, "");
    }
相关问题