我正在嘗試調用控制器方法的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