使用JQuery Ajax Post调用渲染一个简单的ASP.NET MVC PartialView

Use*_*101 13 ajax asp.net-mvc jquery partial-views

我的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);
}
Run Code Online (Sandbox Code Playgroud)

然后在我的视图顶部的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
    }
});
Run Code Online (Sandbox Code Playgroud)

最后我的html:

 <div id="divPartialView">

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

</div>
Run Code Online (Sandbox Code Playgroud)

基本上当我的dropdown标签(有一个名为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

我有什么想法我做错了吗?我用Google搜索了这个死神!

Ali*_*hşi 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);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)