开发者

Passing objects to ASP :NET Webservice through JSON

Im trying to send a custom HTML object from my ASP 2.0 website to my webservice through jQuery ajax. But I cant get it to work.

Everything is parsed correct in my webservice when I drop the ObjectHTML part. But I get an error when I add the ObjectHTML part.

Is it possible to send custom javascript objects?

function SavePage() {
    var rowCount = $('#pageArea div.object').length;
    var i = 1;

    var objects = "[";
    $('.object').each(function(index) {
        var objectHtml = new ObjectHTML($(this).html());
        objects += "{'ObjectID': " + "'" + $(this).attr('objectid') + "', 'ObjectIndex': '" + $(this).attr('objectindex') + "', 'ObjectHTML': " + objectHtml + "}";
        if (i == rowCount)
            objects += ""
        else
            objects += ",";
        i++;
    });
    objects += "]";

    alert("{'objects': " + objects + "}");

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Folder/ObjectService.asmx/SavePage",
        data: "{'objects': " + objects + "}",
        dataType: "json",
        success:
            function(msg) {
                alert("Success!");
            },
        error:
            function(XMLHttpRequest, textStatus, errorThrown) {
                alert("Error Occured: " + errorThrown);
            }
    });
}

function ObjectHTML(rawHtml) {
    this.Html = rawHtml;
}

Webservice code:

[WebMethod(EnableSession = true)]
public string SavePage(List<PageObject> objects)
{
    return "";
}

public class PageObject
{
    private string _objectid, _objectindex;
    private ObjectHTML _objectHtml;

    public string ObjectID
    {
        get { return _objectid; }
        set { _objectid = 开发者_如何学Cvalue; }
    }

    public string ObjectIndex
    {
        get { return _objectindex; }
        set { _objectindex = value; }
    }

    public ObjectHTML ObjectHTML
    {
        get { return _objectHtml; }
        set { _objectHtml = value; }
    }
}

public class ObjectHTML
{
    private string _Html;

    public string Html
    {
        get { return _Html; }
        set { _Html = value; }
    }
}


It looks to me like you are getting a little confused between your C# classes on your server and the Javascript classes in your script.

One thing that you could do is encode your html for JSOn by using JSON.Stringify

var myObject = JSON.stringify({ 
    ObjectId: $(this).attr('objectid'), 
    ObjectIndex: $(this).attr('objectIndex'), 
    ObjectHtml: $(this).html()
});

This will make sure that the html is encoded as valid JSON

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜