在 Asp.net MVC 5 中通过 AJAX 调用部分视图

Calling partial view through AJAX in Asp.net MVC 5

我正在使用以下代码调用局部视图:

$('#btnGetMilestones').click(function () {
$.ajax({
    url: "GetMilestones",
    type: "get",
    success: function (result) {
        $('#milestonesContainer').html(result);
    },
    error: function (xhr, status, error) {
        var msg = "Response failed with status: " + status + "</br>"
        + " Error: " + error;
        $('#milestonesContainer').html(msg);
    },
    complete: function (xhr, status) {
        var doneMsg = "Operation complete with status: " + status;
        alert(doneMsg);
    }
});

});

对于此 ActionResult:

public PartialViewResult GetMilestones()
    {
        return PartialView("_GetMilestones");
    }

局部视图具有项目的里程碑(里程碑和项目是模型)。当我这样调用局部视图时:

<div id="milestonesContainer">
    @Html.Partial("_GetMilestones")
</div>

它工作正常,它获得了项目的所有里程碑。 但是当我尝试通过 ajax 调用部分视图时,会调用错误:响应失败,状态为:错误

错误:请求错误

我在项目的详细信息视图中,所以 url 是这样的 http://localhost:55623/Projects/Details/2002

我是 ajax 和 javascript 的新人,所以如果可能的话,请像对初学者一样解释我。

更新:

在得到一些答案并四处寻找解决方案后,我明白了为什么会出现错误。 我在详细信息视图中,所以 url 是这样的: http://localhost:55623/Projects/Details/2002 看到有一个 ID 参数。 当我进行 ajax 调用时, url 就像这样 http://localhost:55623/Projects/Details 没有 id 参数。所以在 return 我得到一个 400 错误代码

尝试使用 url: "@Url.Action("GetMilestones")" 而不是 url: "GetMilestones",这将呈现操作的实际相对路径,即 /{Controller}/GetMilestones。

还要确保您在控制器中引用了正确的文件名,因为在您的视图中您引用了“_GetMilestone”并且您说它有效,但在您的控制器中您引用了“_GetMilestones ” 如果您的文件名确实是“_GetMilestone”,则无法解析

如果您收到 500 错误,这意味着您可能正在执行操作,并且在呈现局部视图之前或期间发生了异常。尝试通过在浏览器中键入 localhost:port/Projects/GetMilestones 直接导航到局部视图的操作,并查看是否出现异常页面。确保在 Startup class:

的 Configure 方法中执行类似的操作
public void Configure (IApplicationBuilder app) 
{    
    app.UseDeveloperExceptionPage();
}

以我的评论为基础:

抱歉,我对 url 这个词有歧义。这就是我的意思:

除非您在浏览器中的当前 url 是 http://<hostname>/<Controller that contains GetMilestones>,否则您的 AJAX url 是不正确的。 AJAX url 需要 /<Controller>/GetMilestones.

开头 / 将您带到项目的根目录,然后其余部分由您的路由配置处理(通常 /Controller/Method/Id)。这就是 AJAX url 通常需要 /Controller/Method 的原因。但是,如果您在 Index 视图中,您的 url 通常是 http://<hostname>/Controller。因此,如果是这种情况并且您的 AJAX url 只是 Method,它将带您到 http://<hostname>/Controller/Method,因为您没有在 AJAX url 与 /.

您应该考虑利用像 Url.Action 这样的辅助方法来生成您要通过 ajax 调用的操作方法的正确相对路径。如果你的 js 代码在视图中,你可以简单地调用方法

url: "@Url.Action("GetMilestones","Project")",

如果在外部js文件中,你仍然可以使用辅助方法生成路径并将其设置为外部js文件所在的变量。这样做时请确保执行 javascript 命名空间以避免可能覆盖 js 全局变量。

所以在你的view/layout中你可以这样做

<script>
    var myApp = myApp || {};  
    myApp.Urls = myApp.Urls || {};     
    myApp.Urls.mileStoneUrl= '@Url.Action("GetMilestones","Project")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>

在你的PageSpecificExternalJsFile.js文件中,你可以像

一样阅读它
$(function(){
   $('#btnGetMilestones').click(function () {
      $.ajax({
           url: myApp.Urls.mileStoneUrl,
           //Your existing code goes here

           })
     });
});

您需要先将 url 更改为与路线匹配的内容:

 '/<Controller>/GetMilestones/'

从 PartialViewResult 切换到 ActionResult

去 ajax 喜欢:

url: "GetMilestones",
type: "get",
contentType: 'application/html; charset=utf-8',
dataType : 'html'

感谢大家的回答。我的问题得到了答案,也许这有点出乎意料。她是: 更改 ajax 方法:

$('#btnGetMilestones').click(function () { 
        $.ajax({
            url: '/Projects/GetMilestones/' + "?id=" + window.location.href.split('/').pop(),                
            type: "GET",
            success: function (data) {
                $('#milestonesContainer').html(data);
            },
            error: function (xhr, status, error) {
                var msg = "Response failed with status: " + status + "</br>"
                + " Error: " + error;
                $('#milestonesContainer').html(msg);
            },
            complete: function (xhr, status) {
                var doneMsg = "Operation complete with status: " + status;
                alert(doneMsg);
            }
        });
    });

以及操作结果:

public ActionResult GetMilestones(int? id)
    {             
        var forProject = db.Projects.Where(x => x.ID == id).SingleOrDefault();
        return PartialView("_GetMilestones",forProject);
    }

或相同的操作结果,但 ajax 请求略有不同:

$('#btnGetMilestones').click(function () { 
  var id;
   id = @Model.ID;

    $.ajax({
        url: '/Projects/GetMilestones',
        type: "GET",
        data: "id="+id,
        success: function (data) {
            $('#milestonesContainer').html(data);
        },
        error: function (xhr, status, error) {
            var msg = "Response failed with status: " + status + "</br>"
            + " Error: " + error;
            $('#milestonesContainer').html(msg);
        },
        complete: function (xhr, status) {
            var doneMsg = "Operation complete with status: " + status;
            alert(doneMsg);
        }
    });
});