[英]Controller not returning json data to the view in asp.net MVC Ajax
[英]MVC controller not returning JSON data?
我從控制器JsonDetailsProduct
返回Product的JSON數據。 這又是使用Jquery調用的。
但是,Jquery調用的成功函數似乎沒有接收任何數據。 我想我的控制器內部出了問題。
MVC控制器:
public ActionResult JsonDetailsProduct(int id)
{
Product pdt = NWDC.GetProduct(id);
if (pdt == null)
{
// i'm throwing a custom exception here
throw new RecordNotFoundException();
}
else
{
return Json(new {
ProductId = prod.ProductID,
ProductName = prod.ProductName,
UnitPrice = prod.UnitPrice,
UnitsInStock = prod.UnitsInStock,
Discontinued = prod.Discontinued
}, JsonRequestBehavior.AllowGet);
}
}
JQuery調用:
<script type="text/javascript">
$(document).ready(
function(){
alert("About to make the call"); // just added it for my debugging purpose
$.getJSON( "/SlimProductServices/JsonDetailsProduct",
data:{id:$('#txtProductID').val()},
function(productData)
{
alert(productData);
}
);
}
);
任何錯誤設置的問題以及Jquery Call中是否存在任何問題?
編輯此外,我更正了我的Jquery調用的data
參數,但第一個警告框顯示在空白彈出窗口后。
你錯過了id
?
$.getJSON( "/SlimProductServices/JsonDetailsProduct", { 'id': 1 },...
public ActionResult JsonDetailsProduct(int id)
在jquery文檔中查看getJson 。
你從哪里獲得身份證? 如果你只是想在不改變你的jquery調用的情況下測試調用,你可以添加第二個Action方法......
public ActionResult JsonDetailsProduct()
{
Product pdt = NWDC.GetProduct(1); //hard code product Id that exists for testing.
不確定這是否解決了您的問題,我只是簡單地運行了您的代碼。
這是我嘗試過的: -
public ActionResult JsonDetailsProduct(int id)
{
Product pdt = GetProduct(id);
if (pdt == null)
{
// i'm throwing a custom exception here
throw new RecordNotFoundException();
}
else
{
return Json(new Product //Comment:-Added the Object Type
{
ProductId = pdt.ProductId,//Comment:-Sure if its 'prod' and not pdt ?
ProductName = pdt.ProductName,
UnitPrice = pdt.UnitPrice,
UnitsInStock = pdt.UnitsInStock,
Discontinued = pdt.Discontinued
}, JsonRequestBehavior.AllowGet);
}
}
我提出的兩個變化提到它Comment:-
,請看看。
其次,我嘗試使用$.ajax
,其代碼如下: -
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '/SlimProductServices/JsonDetailsProduct/'+$('#txtProductID').val(),
type: 'GET',
//data: $('#txtProductID').val(), //You can un-comment it later
success: function (datos) {
console.log(datos);
},
});
});
</script>
我從我的Action Method
返回了正確的值。 試一試吧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.