Arturito.net

Come to The Dark Side, We Have Cookies!

ASP.NET MVC2 jQuery Form Post Tutorial

with 9 comments

Here is a little tutorial that I wrote about posting form using jQuery and Form plugin.I’m using Visual Studio 2008.
If you want to see how to post form with JSON check my other post:
http://arturito.net/2011/01/25/asp-net-mvc2-jquery-form-post-with-json-tutorial/

1. Open Visual Studio

2. Create MVC2 Empty Web Application

3. Right click Controllers in Solution Explorer and select Add Controller

4. Name it HomeController

5. Right Click on Models in Solution Explorer and select Add Class…

6.  Name it RegisterViewModel

Insert this piece of code:

namespace MVC2JQuery.Models
{
    public class RegisterViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

7. In the Toolbar click Build->Build Solution

8. Go back to HomeController and right click on Index() and select Add View …

    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index() // <-- right click here
        {
            return View();
        }

    }


9. You will be taken to your Index.aspx

10. Now run the application by hitting F5 (Click ok on “Debugging Not Enabled” with option “Modify…”)

11. Now, let’s make it do something. Stop Debugging and go back to Home Controller and add Action:

        [HttpPost]
        public ActionResult Index(RegisterViewModel data)
        {
            // here you can save data to database
            // and return some feedback to the user
            return Content("You submitted: " +  data.FirstName + " " + data.LastName);
        }

12. Your HomeController will look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC2JQuery.Models;

namespace MVC2JQuery.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(RegisterViewModel data)
        {
            // here you can save data to database
            // and return some feedback to the user
            return Content("You submitted: " +  data.FirstName + " " + data.LastName);
        }

    }
}

Build project and Run it.

13. Now go to Scripts in Solution Explorer and remove all file that are in there. We won’t be using them.

14. Download:

jQuery:
http://code.jquery.com/jquery-1.4.4.min.js

jQuery Form Plugin:
https://github.com/malsup/form/raw/master/jquery.form.js

Save them in Scripts folder of your project.


15. Go to Views and chaage Index.aspx as below:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<mvc2JQuery.Models.RegisterViewModel>" %>
<!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>Index</title>
    <script type="text/javascript" src="<%=Url.Content("~/Scripts/jquery-1.4.4.min.js")%>"></script>
    <script type="text/javascript" src="<%=Url.Content("~/Scripts/jquery.form.js")%>"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var options = {
                target: '#result-user', // id of the div where we are going to display result
                beforeSubmit: showRequest,
                success: showResponse,
                type: 'post',
                resetForm: true
            };
            $('#form-user').ajaxForm(options); // id of the form we wish to submit
        });

        function showRequest(formData, jqForm, options) {
            $("#result-user").empty().html('Loading....');
            $("#form-user :input").attr("disabled", true); // disable all form inputs while loading
        }

        function showResponse(responseText, statusText, xhr, $form) {
            $("#result-user").empty().html(responseText);
            $("#form-user :input").attr("disabled", false);
        }
    </script>

</head>
<body>
    <% using (Html.BeginForm("Index","Home",FormMethod.Post, new { id="form-user", name="form-user"})) {%>

        <fieldset>
            <legend>Fields</legend>

            <div class="editor-label">
                <%= Html.LabelFor(model => model.FirstName) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(model => model.FirstName) %>
                <%= Html.ValidationMessageFor(model => model.FirstName) %>
            </div>

            <div class="editor-label">
                <%= Html.LabelFor(model => model.LastName) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(model => model.LastName) %>
                <%= Html.ValidationMessageFor(model => model.LastName) %>
            </div>

            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>

    <% } %>
    <div id="result-user"></div>
</body>
</html>

16. Let’s go back to our HomeController and amend Index action:

        [HttpPost]
        public ActionResult Index(RegisterViewModel data)
        {
            // here you can save data to database
            // and return some feedback to the user

            if(Request.IsAjaxRequest())
                return Content("You submitted: " +  data.FirstName + " " + data.LastName + " using jQuery");
            else
                return Content("You submitted: " + data.FirstName + " " + data.LastName);
        }

17. Build and Run


Here you can download working example


Note:
If you are not getting the same result make sure that:
1.Ids are equal
$(‘#form-user‘).ajaxForm(options);
Html.BeginForm(“Index”,”Home”,FormMethod.Post, new { id=”form-user“, name=”form-user“})

$(“#result-user“).empty().html(responseText);

http://arturito.net/2011/01/25/asp-net-mvc2-jquery-form-post-with-json-tutorial/

Written by guru

December 2nd, 2010 at 8:11 pm

Posted in ASP.NET MVC2,C sharp

  • Pingback: ASP.NET MVC Archived Buzz, Page 1

  • http://dohtml5.com html5 tutorial

    useful info. thanks..soon html5 will take over the web :)

    • arturito

      I hope so too :)

    • Joem

      How much do you really know??  HTML5 will still need code either in the background or as controllers and views.  Whether you decide to go with JavaScript for your entire program, which would be impossible at this point, you still would need a database.  And as far as I knww, JavaScript and any SQL program are not part of HTML5.  And what about all those people that already have legacy machines that work and are in flash.  You can use Wallaby, but who knows how much effort Adobe is going to put into that seeing as how the HTML markup language is a competetor. And HTML5 has been out for a while now, I don’t see much use of it, everything else seems to be getting on just fine and evolving much faster.  So how exactly is HTML going to take over??  I’m curious??

  • Pingback: ASP.NET MVC2 jQuery Form Post with JSON Tutorial « Arturito.net

  • http://profiles.google.com/xiangzhuyuan 柱元 香

    nice! thanks for your share!

  • Lou

    Confused, this looks like Ajax with some jQuery/CSS used to display form textboxes.  The post is done using Ajax, which is ‘HTTPXML!!’ Meaning it is half server and half client.  If this was all jQuery, all that C# that you have there, would not have to be.  You could use jQuery or Javascript OOP.  So, if anyone thinks that they are doing anything that isn’t from chapter one of an Ajax and/or jQuery book, they are being fooled!!

    But if I am wrong, prove it to me.  I will gladly prove it to you.

    • Anonymous

      Mind that this is just an example of integrating jQuery with asp.net mvc2. What I am doing in this example is useless as it can be perfectly done only with Javascript. This example is about HOW to do it. Of course I won’t call the server code just to display what I have just posted. This is useful when you need to validate the post data against the records in the database or perform any other action that needs some complex processing. See for yourself in the point 11. where I comment “     // here you can save data to database
      // and return some feedback to the user

  • Aasd

    asdf