Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Monday, December 16, 2013

Sending javaScript array to server side c# via web service call

Sending javaScript array to server side c# via web service call

I wanted to send a collection of attributers for a set of textbox input html controls to the server side via an AJAX call:

Collect the desired elements and place certain properties in an array:
var inputs = new Array();

    $("[class^=txtEdit]").filter(":input").each(function () {

        var i = { 'ClassName': $(this).attr("class"), 'Id': $(this).attr("id"), 'Val': $(this).val() };

        inputs.push(i);

    });






Make the AJAX call:

var serviceUrl = '..//Tools.asmx/SaveEdits';
    $.ajax({
        type: "POST",
        //data: JSON.stringify(inputs),
        data: '{ "elements":' + JSON.stringify(inputs) + '}',
        contentType: "application/json; charset=utf-8",
        url: serviceUrl,
        dataType: "json",
        success: function (response) {
            if (response.d) {
                //TODO: rebind
            }
            else {
                alert("Save Edits Failed");
            }
        },
        error: function (response) {
            alert("failed service call" + serviceUrl);
        }
 
 
    });






Container class on server:

public class HtmlInput
{
    public string ClassName { get; set; }
    public string Id { get; set; }
    public string Val { get; set; }
 
    public HtmlInput()
    {
 
    }
 
    public HtmlInput(string className, string id, string val)
    {
        this.ClassName = className;
        this.Id = id;
        this.Val = val;
    }
 
}




The web method:
/// 
    /// Saves all the inputs (items, appOverdies) using services
    /// 
    /// colecton of html inputs
    /// error string
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string SaveEdits(HtmlInput[] elements)
    {
 
 
        string ret = string.Empty;
 
        try
        {
 
            foreach (HtmlInput txt in elements)
            {
                //DO some stuff
            }
 
 
            return ret;
 
        }
        catch (Exception e)
        {
            //TODO:  log e.message etc.
 
            return ret += e.Message;
        }
 
    }


Jquery: Displaying Object Property Names and Values

Jquery Displaying Object Property Names and Values

Here is one way to display a JSON object’s property name and value.  I used this to display the results of a test service call to a paging service.

C# class:
 /// 
    /// Container class to hold results of paging service calls
    /// 
    public class PagerComm
    {

        public string Address { get; set; }
        public string Domain { get; set; }
        public string ElaspedTime { get; set; }
        public string Env { get; set; }
        public string Error { get; set; }
        
        
        public PagerComm()
        {

        }

        public PagerComm(string address, string domain, string elaspedTime, string env,string error)
        {
            this.Address = address;
            this.Domain = domain;
            this.ElaspedTime = elaspedTime;
            this.Env = env;
            this.Error = error;

        }





    }


Asmx method returning the class:

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public PagingTools.PagerComm SendTestPage(string tstTyp, string pgrId, string pgrTyp)
    {
        PagingTools.PagerComm ret = new PagingTools.PagerComm();
 
        try
        {
 
            PagingTools.ETestPageService svc = new PagingTools.ETestPageService("local:dxf", "test");
 
            ret = svc.TestEpicPaging(tstTyp, pgrId, pgrTyp);
            
            
            return ret;
        }
 
 
        catch (Exception e)
        {
            //TODO:  log e.message etc.
 
            return ret;
        }
 
 
    }
    




Service call:

function SendTestPage() {
    var serviceUrl = '..//Tools.asmx/SendTestPage';
    var tstTyp = $("#tstTypDdl option:selected").val();
    var pgrId = $("#pgrIdTxt").val();
    var pgrTyp = $("#pgrTypTxt").val();
 
    $.ajax({
        type: "POST",
        data: "{'tstTyp':'" + tstTyp + "', 'pgrId':'" + pgrId + "', 'pgrTyp':'" + pgrTyp + "'}",
        contentType: "application/json; charset=utf-8",
        url: serviceUrl,
        dataType: "json",
        success: function (response) {
            ParsePageComm(response.d);
        },
        error: function (response) {
            alert("failed service call" + serviceUrl);
        }
 
 
    });
 
}


Call back function:

function ParsePageComm(result) {
    if (result) {             
        $("#resultsDiv").html('');
        $.each(result, function (prpNm, prpVl) {
            if (prpNm.indexOf("_") < 0)
                $("#resultsDiv").html($("#resultsDiv").html() + prpNm + ": " + prpVl + "
");
        });
 
    }
    else {
        alert("Error with Service ");
    }
 
 
}




Example UI:

Address:
Domain:
ElaspedTime: 1004.805
Env:
Error: Failed to execute E3C command.


Wednesday, October 17, 2012

JSON serialize with c# deserialize with javascript via pop up window

I created a modal window pop up that shows search results in a gridview. In this gridview there is a checkbox for each row returned. The user can select any rows they want by checking the associated checkbox. One way to send the user's selected data back to the parent window is to use JSON.  Below are code snips on how to to do this.

The c# code serializes the generic list of Icd9 objects into a JSON string.  This new JSON string is sent to a hidden input on the client side. Upon unload of this child window, the window return value is set to the value of the hidden input that was populated on server side. The parent window client code then evals the returned window value.  Once this has been done the value is copied to collection of Icd9 objects.  I for loop my way though this collection accessing the Name and Code properties.



Note:  This works in IE.  I think IE is only browser that supports showModalDialog
           This should work in other browsers if you use winodow.open etc.


Class:
public class Icd9
    {
        public string Name { get; set; }
        public string Code { get; set; }

        public Icd9(string name, string code)
        {
            this.Code = code;
            this.Name = name;
        }

    }


Child Window:
Server side:
using System.Web.Script.Serialization;
 
...
List<CommonTasks.Icd9> selectedCodes = new List<CommonTasks.Icd9>();
 
        for (int i = 0; i < icdGridView.Rows.Count; i++)
        {
            GridViewRow row = icdGridView.Rows[i];
            bool isChecked = ((CheckBox)row.FindControl("selectedRowCb")).Checked;
 
            if (isChecked)
            {
 
                selectedCodes.Add(new CommonTasks.Icd9(icdGridView.Rows[i].Cells[2].Text, icdGridView.Rows[i].Cells[1].Text));
            }
 
 
        }
 
        JavaScriptSerializer js = new JavaScriptSerializer();
        string str = js.Serialize(selectedCodes);
 
        hdnIcd.Value = str;
 
...
 


Client:
 function setWindow_return() {
            var selectedCodes = document.getElementById("hdnIcd");
            window.returnValue = selectedCodes.value;          
        }


Parent Window:
Client:
function GetIcd9()
  {     
    var searchText = document.getElementById("f129").value;
    var url = "Icd.aspx?searchText=" + searchText;
        
    if (searchText.length==0)
        alert(" no value retrieved ");
    else {
          var results = 
           window.showModalDialog(url,"","center:yes;dialogWidth:775px;dialogHeight:480px;resizable:no;status:no;;help:no");
           if(results.length > 0)
           {
             var data = eval(results); 
           
             if(data.length > 0)
             {   
               var icd9Text = "";
               var icd9Code = "";
 
               for(i=0; i < data.length; i++)
               {               
                 icd9Text += data[i].Name + " ";
                 icd9Code += data[i].Code + ",";     
               }
 
               document.getElementById("petsText").value += icd9Text;
               document.getElementById("hidIcd9Code").value += icd9Code;
 
             }
           }
 
         }
  }