Wednesday, February 9, 2011

Post entire form and return JSON data from Asp.net C#

Here is the entire code that will post entire asp.net
form to the target page. The target page will receive
the post data and return the result in the format of JSON data.

Here are the two things one is it will send entire form data,
so you not need to mention every control name with parameter in Ajax.
second one is the target page which receive the data, is return output as
JSON Format.

First you need to download the latest jquery from the jquery site and then copy and
paste the below code and run it.



[1] jQAjaxPostEntireForm.aspx
------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jQAjaxPostEntireForm.aspx.cs" Inherits="jQAjaxPostEntireForm" 

enableViewStateMac="False" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Post entire form and return JSON data from Asp.net C#</title>
    <script type="text/javascript" src="js/jquery-1.6.js"></script>
</head>
<body>
    <form name="emailForm" id="emailForm" runat="server">
    <div>
        <p>Name:<br /><asp:TextBox ID="nName" runat="server"></asp:TextBox>
        </p>
        <p>E-mail:<br /><asp:TextBox ID="email" runat="server"></asp:TextBox>
        </p>
        <p><asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="return doSubmit();" />
        </p>
        <div id="msg"></div>
    </div>
    </form>
</body>

<script type="text/javascript">
    function doSubmit() {
        dataString = $("#emailForm").serialize();
        $.ajax({
            type: "POST",
            url: "jQAjaxPostEntireFormProcess.aspx",
            data: dataString,
            dataType: "json",
            timeout: 5000,
            error: function (xhr, err) {
                $("#msg").html(xhr.responseText + xhr.readyState + xhr.status);
            },
            success: function (data) {
                $("#msg").html(data.yourName + " your Email is :" + data.yourEmail);
            }
        });
        return false;
    }
</script>
</html>
=====================================================
[2] jQAjaxPostEntireForm.aspx.cs
-------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class jQAjaxPostEntireForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

=====================================================
[3] jQAjaxPostEntireFormProcess.aspx
-------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jQAjaxPostEntireFormProcess.aspx.cs"

Inherits="jQAjaxPostEntireFormProcess"  enableViewStateMac="False" %>

=====================================================
[4] jQAjaxPostEntireFormProcess.aspx.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
public partial class jQAjaxPostEntireFormProcess : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       string str;
       JavaScriptSerializer js = new JavaScriptSerializer();
       String yourName=Request.Form["nName"];
       String yourEmail=Request.Form["email"];
       str = "{\"yourName\":\"" + yourName + "\",\"yourEmail\":\"" + yourEmail + "\"}";
       // It is better to use class for JSON, but I have not used it here.
       // because I want just return only two datas.              
       //mailInfo p1 = new mailInfo();
       //p1.yourName = yourName;
       //p1.yourEmail = yourEmail;
       //str = js.Serialize(p1);
       Response.Write(str);
      
   }
}
public class mailInfo
{
    public string yourName, yourEmail;
}