1

I am sending a complex string (which is a combination of the style attribute, ID and label text) from the script using $.ajax() . I went through a couple of questions on similar problems. But maybe I am not able to understand where am I getting it wrong.

This is the script I am using :

    $(".btnSaveStyle").click(function (e) {
        var comp1Style = "";
        var comp2Style = "";

        $(".box").children(".comp1").each(function () {
            var style = $(this).attr('style');
            var title = $(this).text();
            var componentClass = $(this).attr('class');
            comp1Style = comp1Style + style + "#" + componentClass + "#" + title + "$";
        });
        alert(comp1Style); //I get the style here

        $.ajax({
            type: "POST",
            async: true,
            url: 'AjaxRecieveStyle.aspx/GetStyle',
            data: comp1Style
        });

And in the C# I am accessing it in the following way :

 [WebMethod]
    protected void GetStyle(string style)
    {
        var recievedStyle = style;

        Customer customer = (Customer)Session["existing_user"];

        if (customer != null)
        {
            EventComponent eventComponent = new EventComponent();
            string txtComp1 = recievedStyle;
            string[] separateComponents = txtComp1.Split('$');
            string[] individualComponent = new string[5];

            foreach (string position in separateComponents)
            {
                individualComponent = position.Split('#');

                if (individualComponent[0].Equals(""))
                {
                    //do nothing
                }
                else
                {
                    eventComponent.EventID = 1;
                    eventComponent.Image = "";
                    eventComponent.Style = individualComponent[0].ToString();
                    eventComponent.ComponentType = individualComponent[1].ToString();
                    eventComponent.Title = individualComponent[2].ToString();

                    int id = new EventComponentLogic().Insert(eventComponent);
                }
            }
        }
    }

Now :

1) : Should I use a JSON object to pass the data ?

OR

2) : Please show me what am i doing wrong in here ?

Abhishek Ghosh
  • 2,593
  • 3
  • 27
  • 60

3 Answers3

1

1) Yes it's better to send data using JSON - I mean, it'd be much easier to understand what's happening when anyone will look at that code in a year from now. And it's also much easier to extend the protocol based on JSON.

2) I suggest you to add logging at the very beginning of the GetStyle(string style) method. Then please try to get to it by explicitly typing the URL in your browser (or better using PostMan - see below for a link, PostMan will help you with testing POST requests as I see you have a POST request there) and ensure that the web-server code works.

And only if it works then please try your front-end AJAX request.

I suppose that you don't handle POST request correctly in your WebAPI. It will only handle GET requests. Please look at this SO question for details: Simple post to Web Api

3) Link to PostMan: https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en

Community
  • 1
  • 1
Konstantin
  • 339
  • 2
  • 15
  • :If you can please, please show me how would i pass a JSON data in my case.. ? – Abhishek Ghosh Apr 09 '15 at 13:51
  • I have accepted your answer as it gave me an idea to what i was doing wrong.. Please see my answer to as exactly what should be done – Abhishek Ghosh Apr 09 '15 at 14:52
  • 1
    Please excuse me for a delay. I see now that you do not use WebServices, in this case hooking Page_Load is acceptable and very straight-forward. I still do think that Microsoft's WebAPI with strict MVC pattern is a very good approach - as I said, the answer at http://stackoverflow.com/questions/19093603/simple-post-to-web-api gives very good links to start with. – Konstantin Apr 10 '15 at 00:04
  • Regarding samples that use JSON - I believe it is a pretty separate question, and should be discussed as such. And again using Microsoft's MVC helps a lot there. Here's a starting point for you: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client#MediaTypeFormatters. Please note that this article focuses on C# client + C# server, but switching from C# client to JS client should be pretty simple as you're basing on jQuery. JS code will be even simplier than C# code because JSON is natural for JS. – Konstantin Apr 10 '15 at 00:04
  • I follow strictly a 3-tier architecture in my project but haven't used MVC before .. Will have a look at all the links u provided and start using JSON effective immediately :D thank you for suggesting the **PostMan** utility – Abhishek Ghosh Apr 10 '15 at 04:45
0

Did some digging and came up with this link: http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

The source code from the website shows that you may be missing some key features in your ajax call:

function ShowCurrentTime() {
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetCurrentTime",
        data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}

While this is (obviously) intended for their example you see that they set the following attributes that you do not

contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
                alert(response.d);
        }

While the success and failure attributes are definitely optional I believe that setting your content type and datatype would really help you out here.

Pseudonym
  • 2,052
  • 2
  • 17
  • 38
0

I changed my script to the following :

      $.ajax({
                type: "POST",
                async: true,
                url: 'AjaxRecieveStyle.aspx',
                data: { style: comp1Style } //as I want to pass the parameter 'style' which is internally a JSON array.
            });

I fetched the variable style in my C# in the following way (without using [WebServices]) :

I wrote a method GetStyle(string style) to get the data being sent from the ajax call.

Note: I did not call AjaxRecieveStyle/GetStyle from my script as the method is not accessible in my C# method . The data is actually received from the Page_Load method.

I access the variable sent from the script using Request.Params["style"].

My C# method is :

protected void Page_Load(object sender, EventArgs e)
    {
        GetStyle(Request.Params["style"]);
    }

    protected void GetStyle(string style)
    {
        var recievedStyle = style;
        //do something on the recieved data!
    }

This wil be an alternative to anyone who don't want to send JSON data actually !But sending data using JSON format will increase the readability of the code..

Abhishek Ghosh
  • 2,593
  • 3
  • 27
  • 60