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 ,但是没有调用成功的 SetData() 函数,而是在 Google CHromes 控制台上收到 500 内部服务器错误,如下所示:

POST http://localhost:45108/Home/GetPartialDiv/1 500(内部服务器错误) 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 (匿名函数) 5:25 b.event.dispatch jquery-1.9.1.min.js:3 b.event.add.v.handle jquery-1.9.1 .min.js:3

任何想法我做错了什么?我已经用谷歌搜索了这个死了!

4

1 回答 1

20

这行不正确:url: "@Url.Action("GetPartialDiv/")" + $(this).val(),

$.ajax data属性已包含在路由值中。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);
        }
    });
});
于 2013-03-17T21:48:00.157 回答