【问题标题】:Undefined data returned from JSON in ASP.NET从 ASP.NET 中的 JSON 返回的未定义数据
【发布时间】: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>&nbsp; &nbsp;<strong>Load Data </strong>&nbsp;</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


【解决方案1】:

用 ASP.NET MVC 中的 Url.Action() 方法替换静态 URL

"@Url.Action("{action}","{controller}")"代替data-service = "./GetHouseUnits"

希望对你有帮助

【讨论】:

    【解决方案2】:

    网址格式应为../Controller-Name/Action-Name.data-service="./GetHouseUnits" 更改为data-service="../Controller-Name/Action-Name"。 为了确保您使用的是正确的 url,您只需在操作中放置一个断点。 如果您使用正确的 url,则将显示相应的操作以进行迭代,如果不使用该操作,则 url 是错误的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 2021-09-19
      • 2022-01-13
      相关资源
      最近更新 更多