Ajax刷新PartialView与View

时间:2019-05-07 07:14:55

标签: asp.net asp.net-mvc asp.net-core

我正在制作一个非常简单的网站,左侧有一个菜单,右侧有其内容。

例如,CompanyController可以执行以下操作:

public IActionResult Index(int? page)
        {
            var pageNumber = page ?? 1;

            var pageOfCompanies = companyService.ToPagedList(pageNumber, 10);

            ViewBag.OnePageOfCompanies = (IPagedList)pageOfCompanies;

            return PartialView("~/Views/Company/Index.cshtml");
        }

我尝试通过ajax加载每个菜单选项(控制器操作)。我捕获每个元素的点击事件,并且当ajax.get函数结束时,我更新了  内容和浏览器URL。

<script type="text/javascript">

    function getAjaxUrl(url, targetSelector) {

        $.ajax({
            type: "GET",
            url: url,
            dataType: "html",
            cache: false,
            success: function (data) {

                //Refresh content
                $(targetSelector).html(data);

                //Update Navigation URL in browser
                if (url != window.location) {
                    window.history.pushState({ path: url }, '', url);
                }

                //Reload events for new links
                initialize();

            }

        });
    }

    function initialize() {

        $('a').click(function (event) {

            //If href != #
            if (($(this).attr('href') != null || $(this).attr('href') != undefined) &&
                $(this).attr('href').startsWith('/')) {

                //Cancel navigation
                event.preventDefault();

                //Load content
                getAjaxUrl($(this).attr('href'), "#content");

            }
        });
    }

    $(document).ready(function () {

        $("a[class='dropdown-toggle']").click();

        initialize();

    });

</script>

问题是,如果我在浏览器中按F5键,则刷新页面时,它将仅返回“ PartialView”,而不加载菜单。

有人知道这样做的正确方法吗?

0 个答案:

没有答案