Using JQuery And LitJson With ASP.NET Passing Data To ASPX

Default.aspx

   function invokeCastVoteASPX(selectedVote, successFn, errorFn) {

        var url = "/mobile/polls/PollProcessorAsync.aspx";

        //Create list of parameters in the form:
        //{"nam1":"val1","name2":"val2"}       
        jsonData = "{'selectedVote':'" + selectedVote + "'}";

        $.ajax({
            type: "POST",
            url: url,
            contentType: "application/json; charset=utf-8",
            data: jsonData,
            dataType: "json",
            success: successFn,
            error: errorFn
        });
    }


    function CastVote() {

        // Get selected vote
        var selectedVote = GetSelectedVote();
        alert(selectedVote);

        if (selectedVote != null) {
            alert(selectedVote);
            // Cast Vote           
            invokeCastVoteASPX(selectedVote, OnSuccess, OnFailed);
        }
        // Close floating div   

    }

    function OnSuccess(result) {
        alert('CallBack Occured OnSuccess');
        // Close floating div
    }

    function OnFailed(error) {
        alert('CallBack Occured OnFailed');

    }    

    function GetSelectedVote() {
        var list = document.getElementById('<%= rblPollAnswers.ClientID %>'); //Client ID of the radiolist
        var inputs = list.getElementsByTagName("input");
        var selected;
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                break;
            }
        }
        if (selected) {
            return selected.value;
        }

    } 
    
</script>
<asp:Label ID="lblPollQuestion" runat="server"></asp:Label>
<asp:RadioButtonList ID="rblPollAnswers" runat="server" />
<asp:Button ID="btnVote" runat="server" Text="Vote" OnClientClick="CastVote();return false;" />

PollProcessorAsync.aspx

<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        string input = "";

        // Make sure we were posted to
        if (Request.RequestType == "POST")
        {
            try
            {
                // Get posted input stream and convert to a readable string
                StreamReader sr = new StreamReader(Request.InputStream);
                input = sr.ReadToEnd();
            }
            catch
            {
                input = "";
            }

        }


        RenderOutput(input);
    }

    protected void RenderOutput(string request)
    {
        int success = 0;
        string errorMessage = "";
        string errorType = "application";


        if (!String.IsNullOrEmpty(request))
        {
            try
            {
                JsonData json = JsonMapper.ToObject(request);
                if (json != null && json.Count > 0)
                {
                    string selectedVote = (!json["selectedVote"].IsString) ? "" : json["selectedVote"].ToString();


                    // Begin persiting vote to database  
                    Guid userID = Guid.NewGuid();
                    DateTime dateTimeStamp = DateTime.Now;

                    // connection string
                    SqlConnection mySqlConnection = CustomerDAL.GetPrimarySqlConnection();

                    try
                    {
                        try
                        {
                            mySqlConnection.Open();
                        }
                        catch (Exception)
                        {
                            mySqlConnection = CustomerDAL.GetSecondarySqlConnection();
                            mySqlConnection.Open();
                        }

                        // Sql Command object initialized with SQL INSERT
                        SqlCommand mySqlCommand = new SqlCommand("INSERT INTO PollUserResponses (UserID, PollAnswerID, DateTimeStamp) VALUES (@UserID, @PollAnswerID, @DateTimeStamp)", mySqlConnection);
                        mySqlCommand.Parameters.AddWithValue("@UserID", userID);
                        mySqlCommand.Parameters.AddWithValue("@PollAnswerID", Convert.ToInt16(selectedVote));
                        mySqlCommand.Parameters.AddWithValue("@DateTimeStamp", dateTimeStamp);

                        // Execute
                        mySqlCommand.ExecuteNonQuery();

                        success = 1;
                        errorType = "none";
                        errorMessage = "";

                    }
                    catch (Exception ex)
                    {
                        errorMessage = ex.Message;
                    }
                    finally
                    {
                        // close the Sql Connection
                        mySqlConnection.Close();
                    }

                }
            }
            catch (System.Collections.Generic.KeyNotFoundException)
            {
                errorMessage = "KeyNotFoundException";
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }
        }


        string jsonOutputString = @"
{
	'd': {
		's':" + success.ToString() + @", 
		'e': {
			't': '" + errorType + @"',
			'msg': '" + errorMessage + @"'			
		}			
	}
}";


        JsonData jsonOutput = JsonMapper.ToObject(jsonOutputString);

        string output = jsonOutput.ToJson();

        Response.Clear();
        Response.ContentType = "text/plain";
        Response.Write(output);
        Response.End();
    }	
	
</script>

Great Resource For Consuming ASPX in ASP.NET using jQuery

Export DataSet or DataTable to Excel

Function to get the results in datatable

private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    String strConnString = System.Configuration.ConfigurationManager.
         ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        return dt;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}

Export to Excel

protected void ExportToExcel(object sender, EventArgs e)
{
    //Get the data from database into datatable
    string strQuery = "select CustomerID, ContactName, City, PostalCode" +
        " from customers";
    SqlCommand cmd = new SqlCommand(strQuery);
    DataTable dt = GetData(cmd);
 
    //Create a dummy GridView
    GridView GridView1 = new GridView();
    GridView1.AllowPaging = false;
    GridView1.DataSource = dt;
    GridView1.DataBind();
 
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
     "attachment;filename=DataTable.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
 
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        //Apply text style to each Row
        GridView1.Rows[i].Attributes.Add("class", "textmode");
    }
    GridView1.RenderControl(hw);
 
    //style to format numbers to string
    string style = @"<style> .textmode { mso-number-format:\@; } </style>";
    Response.Write(style);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

Source from ASP Snippets

SqlCommand and AddWithValue – The Proper Way Of Adding Parameters To SQL Queries

When adding parameters to SQL queries in code behind ASP.NET pages, the ideal syntax is to use a SQL parameter to help build your query string, rather than creating a text string on the fly.

Example (Bad usage of inline substitution)

mySqlCommand = new SqlCommand("SELECT * FROM [PollAnswers] WHERE ([PollID] = '" + PollID + "') ORDER BY [SortOrder]", mySqlConnection);

Instead use Parameters.AddWithValue and substitute the values in place.

 mySqlCommand = new SqlCommand("SELECT * FROM [PollAnswers] WHERE ([PollID] = @PollID) ORDER BY [SortOrder]", mySqlConnection);

mySqlCommand.Parameters.AddWithValue("@PollID", PollID);

How To Get The Selected Value In A RadioButtonList Via JavaScript

<script type="text/javascript">
    function SelectedRBL() {
        var list = document.getElementById('<%= rblPollAnswers.ClientID %>'); //Client ID of the radiolist
        var inputs = list.getElementsByTagName("input");
        var selected;
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                break;
            }
        }
        if (selected) {
            alert(selected.value);
        }

    } 
</script>

<asp:RadioButtonList ID="rblPollAnswers" runat="server" />
<asp:Button ID="btnVote" runat="server" Text="Vote" OnClientClick="SelectedRBL();return false;" />

Using SqlCommand and AddWithValue Parameters To Execute SQL Insert

public bool PollCastVote(int PollAnswerID)
    {

        bool returnValue = false;

        Guid userID = Guid.NewGuid();
        DateTime dateTimeStamp = DateTime.Now;

        // connection string
        string connectionString = ConfigurationManager.ConnectionStrings["PollConnectionString"].ConnectionString;

        // Sql connection object initialized with connection string used to connect
        using (SqlConnection mySqlConnection = new SqlConnection(connectionString))
        {
            try
            {
                // open the Sql connection
                mySqlConnection.Open();

                // Sql Command object initialized with SQL INSERT
                SqlCommand mySqlCommand = new SqlCommand("INSERT INTO PollUserResponses (UserID, PollAnswerID, DateTimeStamp) VALUES (@UserID, @PollAnswerID, @DateTimeStamp)", mySqlConnection);
                mySqlCommand.Parameters.AddWithValue("@UserID", userID);
                mySqlCommand.Parameters.AddWithValue("@PollAnswerID", PollAnswerID);
                mySqlCommand.Parameters.AddWithValue("@DateTimeStamp", dateTimeStamp);

                // Execute
                mySqlCommand.ExecuteNonQuery();

                returnValue = true;

            }
            catch (Exception ex)
            {

            }
            finally
            {
                // close the Sql Connection
                mySqlConnection.Close();
            }

            return returnValue;

        }
    }

Calling Web Service (asmx) From JavaScript Using PageMethods

TestService.ascx

namespace ScriptManagerService
{
    //The attribute which makes the web service callable from script.
    [System.Web.Script.Services.ScriptService]
    public class TestService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

The above web service code is pretty straight forward. We have a simple “HelloWorld” method which returns a string. What makes this web service special is the “[System.Web.Script.Services.ScriptService]” attribute added on top of the “TestService” web service class. The attribute makes the web service callable from JavaScript. Also when the proxy classes are generated the attribute generates JavaScript object corresponding to the web service class. Once the web service is created now we need to create our web page to invoke the web method. Create a new aspx page and add a “ScriptManager” control to it. Sample aspx page with the “ScriptManager” tag is added below.

<body>
<script language="javascript" type="text/javascript">
function invokeSimpleWebMethod()
{
    ScriptManagerService.TestService.HelloWorld(handleResult);    
} 
 
function handleResult(result)
{
    alert(result);
}

</script>

   <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="scrMgr" runat="server">
            <Services>
                <asp:ServiceReference Path="TestService.asmx" />                
            </Services>
        </asp:ScriptManager>
        <asp:Button ID="btnHW" runat="server" Text="Hello World" OnClientClick="invokeSimpleWebMethod();" />
    </div>
    </form> 
</body>

In the above code we can see that we have a “ScriptManager” server control added. And inside the “Services” tag we have added reference to our local web service using the “ServiceReference” tag. The path attribute of the “ServiceReference” tag has the url of the web service which needs to be invoked. You can add multiple web services by adding additional “ServiceReference” tags. What ASP.NET does here is that it generates JavaScript proxy classes for each of the web services mentioned in the “ServiceReference” tag. All the auto generated JavaScript proxy classes derive from “Sys.Net.WebServiceProxy”.

Also we have an ASP.NET Button server control which calls a “invokeSimpleWebMethod” javascript method on its “OnClientClick” event. In the “invokeSimpleWebMethod” javascript method we have made use of the namespace (in which the web service is defined) followed by the web service name and finally the method name which needs to be invoked. Behind the scene ASP.NET has done the extra work of registering the namespace and creating the proxy classes and also adding the methods defined inside the web service into a proxy JavaScript class. If you notice the “HelloWorld” method takes an argument. The argument is nothing but the name of the JavaScript function which needs to be invoked when the web service method has been successfully executed and results are returned to the browser. You can also pass the name of the function which needs to be invoked when the web service method invocation request fails. We will see the same shortly. The “handleResult” JavaScript method gets called when the asynchronous request is successfully returned. The method gracefully displays the result in an alert message box.

That’ about how to use the “ScriptManager” server control to invoke a web service methods i.e. namespace followed by class name followed by the method name. One thing to note is that “ScriptManager” control can only be used to call web services in the same domain.

More info from source and here.

Real World Example:

PollWSAsync.asmx

<%@ WebService Language="C#" Class="PollWSAsync" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// The following attribute allows the service to 
// be called from script using ASP.NET AJAX.
[System.Web.Script.Services.ScriptService]
public class PollWSAsync : System.Web.Services.WebService
{

    [WebMethod]
    public bool PollCastVote(int PollAnswerID)
    {

        bool returnValue = false;

        Guid userID = Guid.NewGuid();
        DateTime dateTimeStamp = DateTime.Now;

        // connection string
        string connectionString = ConfigurationManager.ConnectionStrings["PollConnectionString"].ConnectionString;

        // Sql connection object initialized with connection string used to connect
        using (SqlConnection mySqlConnection = new SqlConnection(connectionString))
        {
            try
            {
                // open the Sql connection
                mySqlConnection.Open();

                // Sql Command object initialized with SQL INSERT
                SqlCommand mySqlCommand = new SqlCommand("INSERT INTO PollUserResponses (UserID, PollAnswerID, DateTimeStamp) VALUES (@UserID, @PollAnswerID, @DateTimeStamp)", mySqlConnection);
                mySqlCommand.Parameters.AddWithValue("@UserID", userID);
                mySqlCommand.Parameters.AddWithValue("@PollAnswerID", PollAnswerID);
                mySqlCommand.Parameters.AddWithValue("@DateTimeStamp", dateTimeStamp);

                // Execute
                mySqlCommand.ExecuteNonQuery();

                returnValue = true;

            }
            catch (Exception ex)
            {

            }
            finally
            {
                // close the Sql Connection
                mySqlConnection.Close();
            }

            return returnValue;

        }
    }
}

PollControlAsync.ascx

<script runat="server">
protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);      

    }
</script>
<script type="text/javascript">
    function CallService() {
        PollWSAsync.PollCastVote("1",
   Callback);
    }

    function Callback(result) {
        alert('CallBack Occured');
    }
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference Path="PollWSAsync.asmx" />
    </Services>
</asp:ScriptManager>
<asp:Button ID="btnVote" runat="server" Text="Vote" OnClientClick="CallService();return false;" />