重构部分视图的jQuery AJAX调用

Refactor jQuery AJAX call for partial view

本文关键字:AJAX 调用 jQuery 视图 重构部      更新时间:2023-09-26

在我的ASP.net MVC 5应用程序中,我有很多对不同部分视图的调用。为了加载/刷新这些视图,我使用jQuery AJAX。

然而,我最终有很多调用jquery看起来丑陋和冗余。我在想一定有更好的办法。

这是我的脚本在我的index.cshtml,我调用部分视图。

    $(document).ready(function() {
        // load today's level
        $.ajax({
            url: '@Url.Action("_TodayLevel")',
            type: 'GET',
            contentType: 'application/json',
            dataType: 'html',
            //traditional: true,
        }).success(function(e) {
            $('#today-level').html(e);
        });
        // .... truncated to save space. But you get the idea, I have lots of this
        // load host level
        $.ajax({
            url: '@Url.Action("_HostLevel")',
            type: 'GET',
            contentType: 'application/json',
            dataType: 'html',
            //traditional: true,
        }).success(function (e) {
            $('#host-level').html(e);
        });
    });

有更好的方法吗?

在您给出的示例中,您实际上是请求一个HTML页面,然后使用返回的HTML更新页面的一部分。

如果是这种情况,那么您可以简单地使用jQuery的.load()方法:https://api.jquery.com/load/

您可以简单地考虑使用下面的代码来实现您想要的

@{Html.renderaction("_TodayLevel","Controller");}

如果你对这两个视图没有任何控制器操作,你也可以考虑使用

@{Html.renderPartial("_yourViews");}