0

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' }]
4

2 回答 2

1

尝试这个:

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

和 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;
}
于 2013-09-05T05:13:35.650 回答
0

您需要在服务中指定要返回的内容JSON,如下所示:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

省略返回XML

于 2013-09-05T03:59:22.773 回答