Arturito.net

Come to The Dark Side, We Have Cookies!

ASP.NET MVC2 jQuery Form Post with JSON Tutorial

with one comment

In one of the previous post I covered how to post form with ASP.NET MVC2 using jQuery.

Today I will explain how to return data in JSON format. Why return data in JSON format. Well there are several reasons for it:

1. You can easily update several parts of the page without reloading entire page

Imagine that you have ajax login and after successful login the name of the user is updated in the header of the page and content of the saved cart in the right column.

2. It reduces the amount of data sent from the server to the browser.

In a lot of cases developers send data wrapped in html such as:


return Content(“<p class=\”mark-it-green\”>You submitted: “ + data.FirstName + ” “ + data.LastName +“<p>”);


or they send PartialView. But the idea of JSON is to send data only without html tags, which also reduces the traffic.

3. It separates application logic from design

Sending only data using JSON means data doesn’t have to be wrapped in html tags in your controller, you only send pure data. This way one developer can concentrate on developing logic and doesn’t have to think how it will be displayed, leaving web designer to handle presentation part.

Let’s start modifying previous project:

1. Open MVC2JQuery project that can be downloaded here MVC2JQuery at MediaFire

2. Open RegisterViewModel and modified it as below:


public class RegisterViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int NumberOfPosts { get; set; }
public string LastPost { get; set; }
}


3. Open HomeController and make changes as shown below:


[HttpPost]
public ActionResult Index(RegisterViewModel data)
{

// here you can save data to database

// and return some feedback to the user

data.NumberOfPosts = 5;

data.LastPost = “This is my last post”;

if(Request.IsAjaxRequest())

return Json(data);  // here data object is being converted to JSON format

else

return Content(“Please enable JavaScript”);

}


4. Also modify Views/Index accordingly

In the <head> part:


<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 = {
beforeSubmit: showRequest, // call this function before sending data to the server
success: showResponse, // call this function once we have a response form the server
type: ‘post’,
dataType: ‘json’, // important! expecting data type is JSON
resetForm: true
};

$(‘#form-user’).ajaxForm(options);
});

function showRequest(formData, jqForm, options) {
$(“#result-user”).empty().html(‘Loading….’); // display loading
$(“#form-user :input”).attr(“disabled”, true); // disable inputs
}

function showResponse(data, statusText, xhr, $form) {
$(“#result-user”).empty();
$(“#form-user :input”).attr(“disabled”, false);
// here ‘data’ is an object. See below how it is used:
$(“#welcome”).html(“Hello, “ + data.FirstName + ” “ + data.LastName);
$(“#number”).html(“Number of posts: “ + data.NumberOfPosts);
$(“#lastpost”).html(data.LastPost);
}
</script>


In the <body> part:


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

<div style=”float:left” id=”welcome”></div>
<div style=”float:right” id=”number”></div>
<div style=”clear:both;“></div>
<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>
<div style=”border:solid 1px #ccc;margin:10px; id=”lastpost” ></div>
</
body>


5. And we are done! Hit F5 and see result:

ASP.NET MVC2 JQuery JSON Form Post

Here you can download complete source code: http://www.mediafire.com/?ul8wl6o2fe47qk4

Good Luck!

Advertisement

Written by arturito

January 25, 2011 at 9:11 pm

Posted in ASP.NET MVC2, C sharp

One Response

Subscribe to comments with RSS.

  1. [...] with 3 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/ [...]


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.