0

I'm novice in jquery and I have one problem: I have two .aspx files: one of them contain script

<script type ="text/javascript">
    $(document).ready(function () {
        var schemaName = GetURLParameters('schemaName');
        var key = GetURLParameters('key');
        $.post("dataloader.aspx", {
            name: schemaName,
            key: key
        });
    });
</script>

which send parameters to other page, "dataloader.aspx". Here is "dataloader.aspx.cs" code:

protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "application/json";
            var schemaName = Request.Form["name"];
            var key = Request.Form["key"];

            Loader loader = ConnectionManager.getLoader();
            Dictionary<string, string> name_value = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(schemaName))
            {
                var schema = loader.GetSchema(schemaName);
                var qcontext = new SimpleLoader.BOService.QueryContext();
                qcontext.InitQueryContext();

                var element = loader.GetObjectByKey(schema, key);
                var viselems = element._Schema.GetVisibleElems(); 
                var cardElems = viselems.Where(x => !(x is SchemaElemDetail)).ToList();

                foreach (var elem in cardElems)
                {
                    var value = (element.GetValue(elem.Name) ?? "").ToString();
                    if (!string.IsNullOrEmpty(value))
                    {
                        name_value.Add(elem.Name, value);
                    }
                }
                Response.Write(name_value);
                Response.Flush();
                Response.End();
            }

        }

As you can see, I,m adding some data to dictionary. I want to send this dictionary to "clientcard.aspx" client side by jQuery, but i don't know how...Can you help me?? I'll be very grateful.

Sashko Chehotsky
  • 398
  • 2
  • 5
  • 17
  • You need to serialize your dictionary into JSON. No other answer besides mine mentions this step. And it is the most critical! – marteljn Jul 25 '13 at 15:46

3 Answers3

2

A way would be to call a webmethod in dataloader.aspx. Assuming your function's name would be getNameValue, in your aspx page, you'd have a webmethod like this : (You'd basically transfer the code from Page_Load event to this)

[System.Web.Services.WebMethod]
public static Dictionary<string, string> getNameValue(string name, string keyN) 
{
  var schemaName = name;
  var key = keyN;

  Loader loader = ConnectionManager.getLoader();
  Dictionary<string, string> name_value = new Dictionary<string, string>();
  if (!string.IsNullOrEmpty(schemaName))
  {
    var schema = loader.GetSchema(schemaName);
    var qcontext = new SimpleLoader.BOService.QueryContext();
    qcontext.InitQueryContext();

    var element = loader.GetObjectByKey(schema, key);
    var viselems = element._Schema.GetVisibleElems(); 
    var cardElems = viselems.Where(x => !(x is SchemaElemDetail)).ToList();

    foreach (var elem in cardElems)
    {
      var value = (element.GetValue(elem.Name) ?? "").ToString();
      if (!string.IsNullOrEmpty(value))
      {
         name_value.Add(elem.Name, value);
      }
    }    
  }
  return name_value; //will be automatically serialised to JSON because of the dataType specification in ajax call.
}

You'd invoke this function in jQuery in ready like this :

  $(document).ready(function () {
        var schemaName = GetURLParameters('schemaName');
        var key = GetURLParameters('key');
        //just in case
        var data = JSON.stringify({
            name: schemaName,
            keyN: key
        });

        $.ajax({
            type: "POST",
            url: "dataloader.aspx/getNameValue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (xhr, status, error) {
                var msg = JSON.parse(xhr.responseText);
                alert(msg.Message);
            }
          }).done(function (msg) {
            //msg.d will contain your dictionary
          });
  });

The reason its better to use this method is that code becomes reusable. In your current set up, if you want to get the name_value dictionary you'd have to reload the aspx page. Now all you need to do is call this method.

Hope this helps!

krishwader
  • 11,341
  • 1
  • 34
  • 51
  • It won't automatically convert it to JSON, i am pretty sure the default is xml. I think you need to add the attribute `[ScriptMethod(ResponseFormat = ResponseFormat.Json)]`. – marteljn Jul 25 '13 at 15:51
  • @marteljn http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/ – krishwader Jul 25 '13 at 15:56
  • You either need to do what I did or add `[ScriptService]` to the class definition. That attribute is even mentioned in your link... – marteljn Jul 25 '13 at 16:01
  • @marteljn you might be right abt that. But this holds true only for `$.post`. For the `$.ajax` call, where you can set the `dataType`, the ajax will DEFINITELY return a JSON object if set to `json`. So if you set the `dataType` to xml, you will get a parsed XML object (which wont work here BTW bcos `Dictionary` cant be serialised in XML). And the default is `text/html`, not `xml`. See this example for more info. http://stackoverflow.com/questions/6257837/converting-ajax-return-data-to-json – krishwader Jul 25 '13 at 17:11
  • So, i maintain that you neednt add anything in the server side to make serialisation to JSON happen. – krishwader Jul 25 '13 at 17:15
  • @marteljn, you are right. The data contains in XML. You said, that msg.d contains my dictionary. But how can I adress to values in msg.d? I mean, how can I get "elem.Name" and "value"? Sorry,about so "complicated" question, but I dont know jQuery at all...=) – Sashko Chehotsky Jul 26 '13 at 07:21
  • you mean your data is XMl @SashkoChehotsky? – krishwader Jul 26 '13 at 07:34
  • can u pls post that string here? – krishwader Jul 26 '13 at 07:40
  • "schema" - it's loaded XML schema, which contains elements like In C# code, I'm getting "name" attribute and value of this attribute. – Sashko Chehotsky Jul 26 '13 at 07:43
0

It's best to convert to JSON from the DataLoader.aspx page. Then, add a callback in the code segment above:

  $.post("dataloader.aspx", {
        name: schemaName,
        key: key,
        success: function(d) { .. }
  });

The variable "d" contains the response, which would probably be string. You can then use JQuery in the same way to send the data to the next page, either by using JSON.parse and parsing the content, or by passing JSON directly.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
0

In order to create the JSON you want, you are going to need to serialize your dictionary. You can use System.Web.Script.Serialization.JavaScriptSerializer:

var JSSerializer = new JavaScriptSerializer();
Response.Write(JSSerializer.Serialize(name_value));

Then in your JS code:

$(document).ready(function () {
        var schemaName = GetURLParameters('schemaName');
        var key = GetURLParameters('key');
        $.post("dataloader.aspx", {
            name: schemaName,
            key: key
        }, function(data){
        //Here is your success callback and data should be your JSON.
        });
    });

To make this cleaner you might want to consider using an HTTP handler template (.ashx) instead of an .aspx page so you won't have all the over head of an aspx page (i.e. code-behind and view).

marteljn
  • 6,446
  • 3
  • 30
  • 43