MVC3 Posting form data without refreshing a page

In this post, I’ll explain how to post form data without refreshing a page using JQuery ajax and JSON.

Here, I assume a model is used to render form(form elements names same as model properties).

**Step 1:**

Define an action that takes Model as parameter and returns a json object along with attribute HttpPost(simple way)

[HttpPost]
public JsonResult PostMethod(YourModelType m)
{
   // Do something with the model, all the form elements posted are available in the model

   //return json string. Json method that serializes any C# object to json format.
   return Json(your object, JsonRequestBehavior.AllowGet);
}

**Step 2:**

Add javascript function to post data

function PostData(form)
{
  //use only if you wish to validate the form before posting, requires JQuery.validate plugin
 if (!$(form).valid()) {

        return;
    }

    // use $.post, $.ajax can also be used but with some additional parameters
    // 1st parameter is form action to submit, 2nd parameter serialized form data
    // 3rd parameter is the function to be called after successful post and return value
    $.post($(form).attr('action'), $(form).serialize(), function (data) {

           alert('Posted successfully and received data...'+data);


    });
}

Call PostData function to post data on any element action i,e. click etc.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.