MS MVC – jQuery Ajax'd Forms

First, check out the link to the form quickstart:

Within my MS MVC control I have the following:

<form id="frmAddEmployeePlan" action="/Employee/SaveEmployeePlan" method="post">
<%= Html.TextBox("CompanyContributionAmount", "")%>
<input type="submit" value="Save" /> 

That is the form.  I kept it simple for the demo.

Note the action – this is key – I’m sending it to the Employee controller’s ‘SaveEmployeePlan’ action.


At the top of this form I have the following javascript to wire up the ajax form:

<script type="text/javascript">

    $('#frmAddEmployeePlan').ajaxForm(function() {
                alert("Thank you for your comment!");


This is fairly straight forward jQuery stuff.  Basically it intercepts the form request, makes it an ajax call.

Now in my SaveEmployeePlan:

public void SaveEmployeePlan()
            string test = this.ReadFromRequest("CompanyContributionAmount");

I read the request in just to validate it works  – works great.

Very simple example, I would use some of the options here:

ie. in their example it shows this:

// prepare the form when the DOM is ready $(document).ready(function() { var options = { target: '#output1', // target element(s) to be updated with server response beforeSubmit: showRequest, // pre-submit callback success: showResponse // post-submit callback // other available options: //url: url // override for form's 'action' attribute //type: type // 'get' or 'post', override for form's 'method' attribute //dataType: null // 'xml', 'script', or 'json' (expected server response type) //clearForm: true // clear all form fields after successful submit //resetForm: true // reset the form after successful submit // $.ajax options can be used here too, for example: //timeout: 3000 }; // bind form using 'ajaxForm' $('#myForm1').ajaxForm(options); });


The target here is key.  So on my form I would setup a div with an id of ‘output1’ and write the ‘thank you’ into that div and then use the ‘clearForm : true’


public void SaveEmployeePlan()
            //collect form data and save it
            Response.Write("Thank you");

Slick eh?

2 thoughts on “MS MVC – jQuery Ajax'd Forms

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s