Monday, 3 August 2015

Jquery Ajax Call in Asp.net return type is JSON,LIST,Response.Write

(0) Just ajax call 
===========================================================
$.ajax({
                type: "POST",
                url: "WebService2.asmx/SetAutoSuggestionCache",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ cityId1: cityid, hospitalId1: hospitalid, IsHospitalChanged1: IsHospitalChanged }),
                dataType: "json",
                success: function (data) {
                 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
               
                }

            });


(1)Fill Dropdown through jquery ajax url for ajax call is .aspx page

===============================================================
(a)First enable the http request in web.config file
--------------------------------------------------------------------------
web.config

<system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
</system.web>

(b)Create hospitadata.aspx page remove all UI expect page header
---------------------------------------------------------------------------------------------
Hospitaldata.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HospitalData.aspx.cs" Inherits="HospitalData" EnableTheming="false" Theme=""%>

Hospitaldata.aspx.cs


public partial class HospitalData : System.Web.UI.Page
{
    private  GetTransactionData _GetTransactionData = new GetTransactionData();
    public List<RHospitalBO> hospitalList;
  
    protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpRuntime.Cache["HospitalsDataDDl"] == null)
        {
            hospitalList = _GetTransactionData.GetHospitalInformation();
            if (hospitalList.Count > 0)
            {
                HttpRuntime.Cache["HospitalsDataDDl"] = hospitalList;
            }
        }
        else
        {
            hospitalList = (List<RHospitalBO>)HttpRuntime.Cache["HospitalsDataDDl"];
        }
        if(Request.QueryString["cityId"]!=null)
        {
            int citiId = Convert.ToInt32(Request.QueryString["cityId"]);
            var filterData = hospitalList.Where(x => x.cityId == citiId).ToList();
            Response.Write(GenerateOpetions(filterData));
            return;
        }
        Response.Write(GenerateOpetions(hospitalList));
    }

    private string GenerateOpetions(List<RHospitalBO> filterData)
    {
        string result = "<option value='0'>Select an option</option>";
        filterData.ForEach(x =>
        {
            result = string.Concat(result + "<option value=" + x.hospitalId + ">" + x.hospitalName + "</option>");
        });
        return result;
    }
}

(c)Jquery call
---------------------------------------------------------------------------------
<script type="text/javascript">
function bindHospitals() {
            var citiId = $("#ddlCity").val();
            $.ajax({
                url: "HospitalData.aspx?cityId=" + citiId, //Target URL for JSON file
                contentType: 'application/json; charset=utf-8',
                type: 'POST',
                dataType: 'html',
                async: false,
                success: function (data) {
                    $("#ddlHospital").html(data);
                },
                error: function (xhr, status) {
                    console.log(status);
                }
            });
        }
</Script>

(2)Call webservice through JqueryAjax return type is json data
=============================================================
(a)First enable the http request in web.config file
--------------------------------------------------------------------------
web.config

<system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
</system.web>

(b)Create webservice and enable script and session
------------------------------------------------------------------------------
weservice file

using System.Web.Script.Serialization;
[System.Web.Script.Services.ScriptService]

[WebMethod(enableSession: true)]
    public string GetSuggestionData(string Searchtext1)
    {
       List<autosuggestionData> myList = new List<autosuggestionData>();
       
        try
        {
                DataTable Response1 = (DataTable)HttpRuntime.Cache["Response1_wd"];
               
                    foreach (DataRow item in Response1 .Rows)
                    {
                        myList.Add(new autosuggestionData
                        {
                            label = Convert.ToString(item["Name"]),
                            value1 = string.Format("{0}@@@{1}", Convert.ToString(item["Id"]),               Convert.ToString(item["Type"]))
                        });
                    }
        }
        catch (Exception ex)
        {
            
        }
        return new JavaScriptSerializer().Serialize(myList);
    }

(c)Jquery Call
---------------------------------------------------------------------------------------------------

    $.ajax({
                        type: "POST",
                        url: "WebService2.asmx/GetSuggestionData",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify({ Searchtext1: request.term }),
                        success: function (data) {
                         var json_obj = $.parseJSON(data.d);//json return type parse to object type
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            debugger;
                        }
                    });
(3)Call webservice through JqueryAjax return type is list type
=============================================================
(a)First enable the http request in web.config file
--------------------------------------------------------------------------
web.config

<system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
</system.web>

(b)Create webservice and enable script and session
------------------------------------------------------------------------------
weservice file

[System.Web.Script.Services.ScriptService]

[WebMethod(enableSession: true)]
    public List<autosuggestionData> GetSuggestionData(string Searchtext1)
    {
       List<autosuggestionData> myList = new List<autosuggestionData>();
       
        try
        {
                DataTable Response1 = (DataTable)HttpRuntime.Cache["Response1_wd"];
               
                    foreach (DataRow item in Response1 .Rows)
                    {
                        myList.Add(new autosuggestionData
                        {
                            label = Convert.ToString(item["Name"]),
                            value1 = string.Format("{0}@@@{1}", Convert.ToString(item["Id"]),               Convert.ToString(item["Type"]))
                        });
                    }
        }
        catch (Exception ex)
        {
            
        }
       myList;
    }

(c)Jquery Call
---------------------------------------------------------------------------------------------------

    $.ajax({
                        type: "POST",
                        url: "WebService2.asmx/GetSuggestionData",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify({ Searchtext1: request.term }),
                        success: function (data) {
                         var response= data.d;//noneed any parse you can get data like an object
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            debugger;
                        }
                    });

(4)Call webservice through JqueryAjax input  parameter for service  is list type
=============================================================
(a)First enable the http request in web.config file
--------------------------------------------------------------------------
web.config

<system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
</system.web>

(b)Create webservice and enable script and session
------------------------------------------------------------------------------
weservice file

public class IssClassificationBO
{
    public IssClassificationBO()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    //changed by das for reference
    public int? IssClassificationInfoId { get; set; }
    public int? PatientId { get; set; }
    public string IssClassificationDate { get; set; }
    public string Stage { get; set; }
    public string Albumin { get; set; }
    public string Microglobulin { get; set; }
    public string CreatedIP { get; set; }
    public int CreatedBy { get; set; }
  
    public DateTime ConvertedIssClassificationDate
    {
        get { return getdate(); }
        set { value = getdate(); }
    }
    public DateTime getdate()
    {
        string[] t = IssClassificationDate.Split('/');
        DateTime dt = new DateTime(Convert.ToInt32(t[2]), Convert.ToInt32(t[1]), Convert.ToInt32(t[0]));
        return dt;
    }
}

[System.Web.Script.Services.ScriptService]
 public void SaveDiagnosisDetails(List<DiagnosisDetailsBO> objDiagnosisDetailsBO    {

}

(c)Jquery Call
---------------------------------------------------------------------------------------------------
Input list object creation
 
var issClassificationArrayObject = new Array();

 var IssClassificationBo = {
                                'PatientId': '<%= PatientId %>',
                                'IssClassificationInfoId': "1",
                                'IssClassificationDate': "1",
                                'Albumin': "1",
                                'Microglobulin': "1",
                                'Stage': stage,
                                'CreatedBy': '16/10/2015',
                            'CreatedIP': '::1'
                            }
                            issClassificationArrayObject.push(IssClassificationBo);


var IssClassificationBo1 = {
                                'PatientId': '<%= PatientId %>',
                                'IssClassificationInfoId': "1",
                                'IssClassificationDate': "1",
                                'Albumin': "1",
                                'Microglobulin': "1",
                                'Stage': stage,
                                'CreatedBy': '16/10/2015',
                                'CreatedIP': '::1'
                            }

  issClassificationArrayObject.push(IssClassificationBo1);

 Jquery call
 
    $.ajax({
                        type: "POST",
                        url: "WebService2.asmx/GetSuggestionData",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify({ objDiagnosisDetailsBO    : issClassificationArrayObject }),
                        success: function (data) {

                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            debugger;
                        }
                    });

Precautions
======================================================================
 (1)If we have datetype property in out list object webservice will accept date input MM/DD/YYYY formate only 

Ex. 10/20/2015 accept format 20/10/2015 not accepted formate

incase wants to handle DD/MM/YYYY formate then take string formate property in class in json data assign ui date to this formate. and create another Property for generate required formate date.

EX.

public string IssClassificationDate { get; set; }==>This one json data property
public DateTime ConvertedIssClassificationDate==>This one database send property
    {
        get { return getdate(); }
        set { value = getdate(); }
    }
    public DateTime getdate()
    {
        string[] t = IssClassificationDate.Split('/');
        DateTime dt = new DateTime(Convert.ToInt32(t[2]), Convert.ToInt32(t[1]), Convert.ToInt32(t[0]));
        return dt;
    }

(2)Incase any integer type properties in class its better make it as nullable type.Incase user not send any data for this property service will work fine other wise service will not call from ajax call.

EX.
public int? IssClassificationInfoId { get; set; }

5 comments: