Rendering a simple ASP.NET MVC PartialView using JQuery Ajax Post call

大兔子大兔子 提交于 2019-12-03 05:56:56

问题


I have the following code in my MVC controller:

[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);
}

Then this in my javascript at the top of my view:

$(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
    }
});

Then finally my html:

 <div id="divPartialView">

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

</div>

Essentially when a my dropdown tag (which has a class called SelectedCustomer) has an onchange fired it should fire the post call. Which it does and I can debug into my controller and it even goes back successfully passes back the PartialViewResult but then the success SetData() function doesnt get called and instead I get a 500 internal server error as below on Google CHromes console:

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

Any ideas what I'm doing wrong? I've googled this one to death!


回答1:


this line is not true: url: "@Url.Action("GetPartialDiv/")" + $(this).val(),

$.ajax data attribute is already included route value. So just define url in url attribute. write route value in data attribute.

$(".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);
        }
    });
});


来源:https://stackoverflow.com/questions/15466597/rendering-a-simple-asp-net-mvc-partialview-using-jquery-ajax-post-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!