Cyval
Cyval

Reputation: 2519

Undefined data returned from JSON in ASP.NET

I have a simple web application that has a HouseUnitController with an action that returns a 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);
    }

In my view, I have:

<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>

When I browse localhost:62516/HouseUnits/GetHouseUnits, I can see the JSON result that was returned. However, when I click the button, I do not receive any data. Here is my script file which is working for other html pages:

$('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);

});

I have a feeling that it has something to do with the url in the button, because it seems that the data that was returned from AJAX was 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);
    }
});

}

Can someone please help me with this problem? I've tried ./GetHouseUnits and ../GetHouseUnits but it doesn't work. Thanks.

Upvotes: 0

Views: 65

Answers (2)

anand
anand

Reputation: 1579

The url should be in the format of ../Controller-Name/Action-Name. Change the data-service="./GetHouseUnits" to data-service="../Controller-Name/Action-Name". To make sure that you are using the correct url, just you have to place a break point in the action. If you are using correct url, then the respective action will shown for iteration and if not using the action, then the url is wrong.

Upvotes: 0

Frebin Francis
Frebin Francis

Reputation: 1915

Replace your static URL's with the Url.Action() method in ASP.NET MVC

instead of data-service = "./GetHouseUnits" use "@Url.Action("{action}","{controller}")"

Hope this helps

Upvotes: 2

Related Questions