2013-03-17 95 views
13

我在我的MVC控制器下面的代码:我的视图顶部渲染一个简单的ASP.NET MVC PartialView使用JQuery的Ajax调用后

[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开了它应该发射岗位电话。其中它,我可以调试到我的控制器,它甚至可以追溯到成功传回PartialViewResult但随后成功的SetData()函数犯规被调用,而是我得到一个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

任何想法我做错了什么?我已经把这个一个人杀了!

回答

18

此行是不正确的: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); 
     } 
    }); 
}); 
+0

不错的地方,只是意识到它没有意义我这样做,并将它作为查询字符串/路由值传递。但我认为我发现问题是我的分部观点,我不得不改变它是返回PartialView(“MyPartialView”,guestResponse); – User101 2013-03-17 21:52:48

+0

我的意思是返回PartialView(“〜/ Views/MyPartialView.cshtml”,guestResponse);相反,这很奇怪,因为它应该只是不工作? – User101 2013-03-17 21:53:09

+0

你必须完全指定的观点是,究其原因是因为你没有把它放在默认的位置之一,即〜/查看/ WhateverTheControllerNameIs/MyPartialView.cshtml或〜/查看/共享/ MyPartialView.cshtml – StanK 2013-03-18 01:03:55