我的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 (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
任何想法我做错了什么?我已经把这个死了!
解决方法
这行不是真的:url:“@ Url.Action(”GetPartialDiv /“)”$(this).val(),
$.ajax数据属性已经包含路由值.所以只需在url属性中定义url.在数据属性中写入路由值.
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: '@Url.Action("GetPartialDiv","Home")',XMLHttpRequest) {
SetData(data);
}
});
});