【发布时间】:2016-01-13 05:20:10
【问题描述】:
我有一个简单的 Web 应用程序,它有一个 HouseUnitController 和一个返回 JSONResult 的操作。
public JsonResult GetHouseUnits()
{
var houseUnits = db.HouseUnits.Include(h => h.HouseModel).Include(h => h.Site)
.Select(h => new {
h.Block,
h.Lot,
h.HouseModel.ModelName,
h.Site.SiteName,
h.IsSold,
h.FloorArea,
h.LotArea,
h.Price
});
return Json(houseUnits, JsonRequestBehavior.AllowGet);
}
在我看来,我有:
<button data-retrieve data-view="tree" data-service = "./GetHouseUnits" data-container="#view" class="btn btn-warning btn-sm" > <span class="glyphicon glyphicon-arrow-down"></span> <strong>Load Data </strong> </button>
当我浏览localhost:62516/HouseUnits/GetHouseUnits 时,我可以看到返回的 JSON 结果。但是,当我单击按钮时,我没有收到任何数据。这是我的脚本文件,它适用于其他 html 页面:
$('button[data-retrieve]').click(function(){
var treeHeaderLimit = 2;
var APIurl = $(this).data('service');
var view = $(this).data("view");
var dataCount = 5;
var selId = $(this).data("container");
createView(APIurl, selId, view, dataCount, treeHeaderLimit);
});
感觉跟按钮里面的url有关系,因为好像AJAX返回的数据是undefined。
function createView(APIurl, selId, viewType, dataCount, treeHeaderLimit){
$.ajax({
url: APIurl,
type: "GET",
contentType: "application/json",
dataType: "json", //This is used to avoid `No-Access-Control-Allow-Origin` header error
success:function(data){
if (viewType=="tree"){
generateTree(data, selId, dataCount, treeHeaderLimit)
} else{
generateTable(data, selId, dataCount);
}
},
error: function (err) {
alert(err);
}
});
}
有人可以帮我解决这个问题吗?我试过./GetHouseUnits 和../GetHouseUnits 但它不起作用。谢谢。
【问题讨论】:
-
尝试使用 Url.Action() 而不是静态 URL
-
您尝试
HouseUnits/GetHouseUnits的数据服务属性了吗? -
谢谢@FrebinFrancis。将其发布为答案,以便我接受。
标签: javascript jquery asp.net json