views:

49

answers:

1

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

    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; }
    }
}
+2  A: 

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

Daniel Dyson
Lol.. my bad, I did not change my C# object from `ObjectHTML` to `string` looks like it works :D
Martin
Oh good. Glad to hear it
Daniel Dyson