views:

52

answers:

3

here is my web service :

public class Header : System.Web.Services.WebService {
    public Header () {}
    [WebMethod]
    public string GetArchive(string PageID)
    {
        StringBuilder sb = new StringBuilder();
        BusinessRules.News news = new BusinessRules.News();
        BusinessObject.NewsItemList newsList =
            news.GetListbySectionID(int.Parse(PageID));

        foreach (BusinessObject.NewsItem item in newsList)
        {
            sb.Append(item.ID + " : " + item.Date);
        }
        return sb.ToString();
    }

}

where

<body>
    <form id="form1" runat="server">
    <div>        
        <div runat="server" id="Content">
        </div>
        <div>
            <a id="LinkBtnAll" href="#">View</a>
        </div>
    </div>
    </form>
</body>

and

<script type="text/javascript">
    $(document).ready(function () {

        var ParamValue = $.getUrlVar("id");        

        $('#LinkBtnAll').click(function () {
            $.ajax({ type: "POST",
                url: "Services/Header.asmx/GetArchive",
                data: "{'PageID'," + ParamValue + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                cache: false,
                success: function (msg) {
                    $('#Content').text(msg.d);
                }
            })
            return false;
        });   
    });            
</script>

it doesn't work is anyone who can help me ?

A: 

I have written a jquery plugin for this purpose. It makes your call and parameter passing very easier. you can download it from: http://www.4shared.com/file/Y72VBeLc/PageMethod.html

Kamyar
A: 

Your JSON syntax is wrong, for one. The entire thing needs to be enclosed in braces, your properties need to be separated by commas, and you should quote your property names and probably values, since the values likely have spaces.

public class Header : System.Web.Services.WebService
{
    public Header () {}

    [WebMethod]
    public string GetArchive(string PageID)
    {
        StringBuilder sb = new StringBuilder("{");
        BusinessRules.News news = new BusinessRules.News();
        BusinessObject.NewsItemList newsList = news.GetListbySectionID(int.Parse(PageID));
        foreach (BusinessObject.NewsItem item in newsList)
        {
            sb.Append("\"" + item.ID + "\" : \"" + item.Date + "\"," );
        }
        return sb.ToString().TrimEnd(",") + "}";
    }
}

Having said that, a better way would be to use a JSON serializer. Note the format in the following example will be different a collection of JSON objects rather than a single JSON object holding all the properties. You'll have to change your client code to account for this.

public class Header : System.Web.Services.WebService
{
    private class Article
    {
        public string ID { get; set; }
        public DateTime Date { get; set; }
    }

    public Header () {}

    [WebMethod]
    public string GetArchive(string PageID)
    {
        var articles = new List<Article>();
        BusinessRules.News news = new BusinessRules.News();
        BusinessObject.NewsItemList newsList = news.GetListbySectionID(int.Parse(PageID));
        var articles = newsList.Select( a => new Article
                       {
                           ID = a.ID,
                           Date = a.Date
                       };
        var stream = new MemoryStream();
        using (var serializer = new DataContractJsonSerializer(articles.GetType());
        serializer.WriteObject( stream, articles );
        return Encoding.Default.GetString( stream.ToArray() );
    }
} 
tvanfosson
+1  A: 

First of all for should use [ScriptMethod (ResponseFormat = ResponseFormat.Json)] attribute for the web method or configure the same in the web.config if you use .NET 4.0. In both cases you need not impelemnt any kind of JSON serialization manually. Instead of that you can just return the object itself. In other words you should follow the advice of tvanfosson, but return the List<Article> directly:

[System.Web.Script.Services.ScriptService]
public class Header : System.Web.Services.WebService {
    [WebMethod, ScriptMethod (ResponseFormat = ResponseFormat.Json)]
    public List<Article> GetArchive(int PageID)
    {
        BusinessRules.News news = new BusinessRules.News();
        BusinessObject.NewsItemList newsList = news.GetListbySectionID(PageID));
        return newsList.Select (a => new Article
                       {
                           ID = a.ID,
                           Date = a.Date
                       });
    }

    public class Article
    {
        public string ID { get; set; }
        public string Date { get; set; }
    }
}

I changed the type of the input parameter PageID from the string to int to show that the input parameters must not be a string only. It can be a class instance also (see my old another).

On the client side inside of the $(document).ready(function () {/*the code here you will see below*/});:

var ParamValue = $.getUrlVar("id");
var pageID = parseInt(ParamValue,10);

$('#LinkBtnAll').click(function () {
    $.ajax({
        type: "POST",
        url: "Services/Header.asmx/GetArchive",
        data: {PageID: JSON.stringify(pageID)},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $('#Content').text(msg.d);
        }
    })
    return false;
});

the decoding of the results from msg.d you should implement in other way, because the msg.d is an array, but it would be a simple JavaScript code.

I recommend you to look at the old answer and another one for more information.

Oleg