Frzzy Frzzy - 1 month ago 15
jQuery Question

Pass object from asp-c# to jquery

i want to pass an object from c# to jquery but it didn't work. Here is my code
c#:

public class ImgLink
{
public string img;
}

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class ImgService : WebService
{
List<ImgLink> Imgs = new List<ImgLink>{
new ImgLink{img="/kazvan-1.jpg"},
new ImgLink{img="/kazvan-2.jpg"},
new ImgLink{img="/wojno-3.jpg"}
};
[WebMethod]
public List<ImgLink> GetAllImgs()
{
return Imgs;
}
}


Script:



function getImgs() {
var myArray = [];
$.ajax({
type: "POST",
url: "ImgService/GetAllImgs",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
$.each(cars, function (index, car) {
myArray.push({ "image": +car.img });
});
alert("success");
},
failure: function (msg) {
alert("fail");
}
});
return myArray;
}


my result: MyArray has nothing.

expected result:

myArray = [{ image: '/kazvan-1.jpg' },{ image: '/kazvan-2.jpg' },{ image: '/wojno-3.jpg' }]

Answer

Try this:

public class ImgLink
{
    public string img;
}


    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
     [System.Web.Script.Services.ScriptService]
public class ImgService : WebService
{
    List<ImgLink> Imgs = new List<ImgLink>{
        new ImgLink{img="/kazvan-1.jpg"},
        new ImgLink{img="/kazvan-2.jpg"},
        new ImgLink{img="/wojno-3.jpg"}
    };
    [WebMethod]
    public List<ImgLink> GetAllImgs()
    {
        return Imgs;
    }
}

and jQuery:

function getImgs() {
     var myArray = [];
     $.ajax({
         type: "POST",
         url: "ImgService/GetAllImgs",
         data: "{}",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (response) {
             var cars = response.d;
             $.map(cars, function (item) {//use .map method
                 myArray.push({ "image": +item.img });
             });
             alert("success");
         },
         failure: function (msg) {
             alert("fail");
         }
    });
    return myArray;
}