This post has been migrated from www.experimentsincode.com, we apologise if some of the images or content is missing

I recently had to look into how to make an Ajax post back while using ASP.NET, my immediate thought was to use the ASP.NET Ajax UpdatePanel. However the client did not use the Ajax library and didn't want to use since their site already used JQuery. My initial thought was that this is going to be a headache, due to the viewstate and ensuring that controls are married up correctly on post back so events fire. However to my surprise the whole process was very simple!! To start we need to create a page that contains our form:
        <form id="form1" runat="server">
        <div>
            <asp:Literal runat="server" ID="outputTest" />
            <asp:Button runat="server" ID="submit" Text="Submit" />
        </div>
        </form>
You may notice that I haven't specified any input elements, I am going to add these to the form dynamically, you can add them in the page but I wanted to make a slightly more complicated demonstration.  The code behind for this page is:
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
   {
        outputTest.Text = "";
        Response.Write(DateTime.Now.ToString());
    }

    public int Count
    {
        get
        {
            if (Session["count"] == null) Session["count"] = 1;
            return (int) Session["count"];
        }
        set
        {
            Session["count"] = value;
        }
    }

    protected override void CreateChildControls()
    {

        for (int i = 0; i < Count; i++)         {
             TextBox txt = new TextBox();
             txt.TextChanged += (object sender, EventArgs e) =>
            {
                TextBox txt1 = (TextBox)sender;
                outputTest.Text += txt1.Text;
            };
            this.Form.Controls.Add(txt);
        }

        Count++;

        base.CreateChildControls();
    }
}
Every time the page loads an extra text box is added to the page.  On post back any text boxes that have changed will write their output to the literal control. If you test this page now you should see the time being printed at the top of the page, a few text boxes below that and if you enter some content and submit the form the content should be written to the page:

Now we want to turn this into an Ajax form using jQuery. To make things a lot simpler we are going to use the jQuery Form Plugin, we add the appropriate script elements to link to both the jQuery core and the form plugin:
    <script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="http://github.com/malsup/form/raw/master/jquery.form.js?v2.43" type="text/javascript"></script>
Now the code to turn the form into an Ajax form:
    <script type="text/javascript">
        $(document).ready(function() {
            SetupForm();
        });
        function SetupForm() {
            $('#<%= form1.ClientID %>').ajaxForm({
                target: 'form',
                replaceTarget: true,
                data: { 'ajax': 'true' },
                success: function() {

                    SetupForm();
                }
            });
       }
    </script>
Notice that we have to create a success function that calls the SetupForm method again, this will wire up the form again once we receive the response from the server. The second item of interest is:
 data:{'ajax','true'}
This sends back an additional form element to the server which we can use to tell that an Ajax submission has been made. We now need to make one more alteration to out codebehind to get the whole thing to work. We now need to override the RenderControl method:
    public override void RenderControl(HtmlTextWriter writer)
    {

        if (Request.Form["ajax"] != null)
        {
            Response.Clear();
            Form.RenderControl(writer);
        }
        else
        {
            base.Render(writer);
        }
    }
Here we check to see if the form was submitted by the Ajax from submission, if it was we clear any response and just render the form. Otherwise we render the rest of the page as a normal request. Compile and run the page, you should notice that the date and time at the top of the page no longer update as the form is submitted.
comments powered by Disqus