Saturday, 28 February 2015

read json in c#

Reading the JSON file passing from Jscript file and read that in C# Code

Suppose you are creating the JSON file like below;

function GetInsertedData() {
    var CustomerDetailsModels = {
        CustomerDetailId: $("#hdnId").val(),
        ClinicName: $("#txtClinicName").val(),
       PhoneNumber: $("#txtPhoneNumber").val(),
        UserName: $("#txtUserName").val(),
        Password: $("#txtPassword").val(),
        // DateOfRegistration: $("#DateOfRegistration").val(),
        ValidaityDate: $("#txtValidaityDate").val(),
        ActiveDate: $("#txtDateOfActivation").val(),
        Address1: $("#txtAddress1").val(),

        Address2: $("#txtAddress2").val(),
        CountryId: $("#ddlSelecteCountry").val(),
        StateId: $("#ddlSelectState").val(),
        DisctrictId: $("#ddlDistrict").val(),
        PinCode: $("#txtPincode").val(),
        EmailId: $("#txtEmailID").val(),
        Website: $("#txtWebsite").val(),
        OfficeNumber: $("#txtOfficeNumber").val(),
        NumberOfUser: $("#ddlAllowedNumberUser").val(),
        IsActive: $("#chkISActive").val(),
        IsPaid: $("#chkISPaid").val(),
        AmountPaid: $("#txtPaidAmount").val()


    };
    return CustomerDetailsModels;
}

Passing that JSON file to C# by using the below AJAX Call;
You need to do the stringify  to the JSON file or Deserialize it  like below code;
  var DTO = JSON.stringify(GetInsertedData());

Now Passing the JSON data C# code like below code
////Insert the  records to database
function AddRecords() {
    $("#dvSuccess").visible = false;
    $("#hdnId").val("");
    var url = 'CustomerDetails.aspx/InsertRecords';
    var DTO = JSON.stringify(GetInsertedData()); //Sys.Serialization.JavaScriptSerializer.serialize(GetInsertedData()); //

    $.ajax({
        type: 'POST',
        url: url,
        data: "{'DTO':'" + DTO + "'}",
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (response) {
            $("#hdnId").val("");
            ClearData();
            $('#myModal').modal('hide');
            $(".alert-success").show();
            $(".alert-success").text("New Customer Details Save Successfully!!");
            $(".alert-danger").hide();
            $(".alert-danger").text("");
            LoadData();

        },
        error: OnErrorCall
    });
}
Your JSON will created like Below;

{"CustomerDetailId":"","ClinicName":"test","PhoneNumber":"343453543","UserName":"test","Password":"test","ValidaityDate":"18/02/2015","ActiveDate":"12/02/2015","Address1":"asas","Address2":"asas","CountryId":"148","StateId":"5","DisctrictId":"1","PinCode":"1212","EmailId":"sasas","Website":"asas","OfficeNumber":"12121","AmountPaid":"1212"}
In server side method will be like Below;


[WebMethod(EnableSession = true)]
        public static int InsertRecords(string DTO)
        {
           // CustomerDetailsModels oPassedVal = Obj.First();
            CustomBAL<CustomerDetailsModels> obj = new CustomBAL<CustomerDetailsModels>();
             CustomerDetailsModels objValue = new CustomerDetailsModels();

             Dictionary<string, object> oPassedVal = DTO.JSONSerialize();
objValue.ClinicName = (string)oPassedVal[enumCustomerDetailsModels.ClinicName.ToString()];
             objValue.PhoneNumber = (string)oPassedVal[enumCustomerDetailsModels.PhoneNumber.ToString()];
}

Code for reading the JSON is below

             Dictionary<string, object> oPassedVal = DTO.JSONSerialize();
Here I created the extension method which make easir to convert the JSON Deserializer as;
public static  class ExtensionMethods
    {
        /// <summary>
        /// Serialization of JSON Object and get into the form of disctionay
        /// </summary>
        /// <param name="DTO"></param>
        /// <returns></returns>
        public static Dictionary<string, object> JSONSerialize(this String DTO)
        {
            object oPassedVal =  new JavaScriptSerializer().DeserializeObject(DTO);
            Dictionary<string, object> dictionary = (Dictionary<string, object>)oPassedVal;
            return dictionary;
        }


       
    }


Congratulations now you can read the JSON from JQUERY

No comments:

Post a Comment