我正在尝试调用控制器方法的ajax调用。没有参数,它工作正常。一旦我添加参数,我总是收到一个空参数给cotroller。我想我已经正确地完成了在ajax调用中传递的参数。在Ajax调用中传递参数
<script type="text/javascript">
$(document).ready(function() {
$('#lstStock').change(function() {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: '{"stockID":"' + dropDownID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data.Result);
}
function errorFunc() {
alert('error');
}
})
});
</script>
控制器:
[HttpGet]
public ActionResult GetStockPrice()
{
return View();
}
[HttpPost]
[ActionName("GetStockPrice")]
public ActionResult GetStockPrice1(string stockID)//I get the null parameter here
{
DeliveryRepository rep = new DeliveryRepository();
var value = rep.GetStockPrice(stockID);
return Json(new { Result = value }, JsonRequestBehavior.AllowGet);
}
与您的解决方案,我也必须删除contentType:“application/json; charset = UTF-8”,然后才开始工作。任何想法? – chamara 2013-05-07 09:00:08
你需要'contentType:“application/json”'在进行stringify时告诉浏览器将数据作为json发送。默认的contentType在传递诸如'{stockID:dropDownID}'的数据时会起作用,因为它被解释为有效的json对象/数据。 – 2013-05-07 09:11:19