使用JQuery Ajax Post调用呈现简单的ASP.NET MVC PartialView

13

我在我的MVC控制器中有以下代码:

[HttpPost]
public  PartialViewResult GetPartialDiv(int id /* drop down value */)
{
    PartyInvites.Models.GuestResponse guestResponse = new PartyInvites.Models.GuestResponse();
    guestResponse.Name = "this was generated from this ddl id:";

    return PartialView("MyPartialView", guestResponse);
}

然后在我的视图顶部的javascript中添加如下代码:

$(document).ready(function () {

$(".SelectedCustomer").change( function (event) {
    $.ajax({
        url: "@Url.Action("GetPartialDiv/")" + $(this).val(),
        data: { id : $(this).val() /* add other additional parameters */ },
        cache: false,
        type: "POST",
        dataType: "html",
        success: function (data, textStatus, XMLHttpRequest) {
            SetData(data);
        }
    });

});

    function SetData(data)
    {
        $("#divPartialView").html( data ); // HTML DOM replace
    }
});

然后最终是我的HTML:

 <div id="divPartialView">

    @Html.Partial("~/Views/MyPartialView.cshtml", Model)

</div>

基本上当我的下拉标签(它有一个名为SelectedCustomer的类)触发了onchange事件时,它应该触发POST调用。它确实这样做了,我可以调试进入我的控制器,它甚至成功地返回了PartialViewResult,但是success SetData()函数没有被调用,而是在Google Chrome控制台上出现500内部服务器错误,如下所示:

POST http://localhost:45108/Home/GetPartialDiv/1 500 (Internal Server Error) jquery-1.9.1.min.js:5 b.ajaxTransport.send jquery-1.9.1.min.js:5 b.extend.ajax jquery-1.9.1.min.js:5 (anonymous function) 5:25 b.event.dispatch jquery-1.9.1.min.js:3 b.event.add.v.handle jquery-1.9.1.min.js:3

你有任何想法我在哪里做错了吗?我已经谷歌搜索过无数次!

1个回答

20

这一行不是真的:url: "@Url.Action("GetPartialDiv/")" + $(this).val(),

$.ajaxdata属性已经包含了路由值,因此只需在url属性中定义URL。将路由值写入data属性中。

$(".SelectedCustomer").change( function (event) {
    $.ajax({
        url: '@Url.Action("GetPartialDiv", "Home")',
        data: { id : $(this).val() /* add other additional parameters */ },
        cache: false,
        type: "POST",
        dataType: "html",
        success: function (data, textStatus, XMLHttpRequest) {
            SetData(data);
        }
    });
});

不错的发现,我意识到将其作为查询字符串/路由值传递并没有意义。然而,我认为我找到了问题所在,是我的部分视图,我必须将其更改为返回PartialView(“MyPartialView”,guestResponse); - User101
我是指返回PartialView("~/Views/MyPartialView.cshtml", guestResponse); 而不是其他奇怪的方式,因为它应该可以正常工作,不是吗? - User101
你必须完全指定视图所在的位置,是因为你没有将它放置在默认位置之一,即/Views/WhateverTheControllerNameIs/MyPartialView.cshtml或/Views/Shared/MyPartialView.cshtml。 - StanK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接