Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Friday, 19 July 2013

Using Partial View and AJAX for Validation - with jQuery Ajax

In the previous post I wrote about using partial view for validation with Ajax.BeginForm. If we want to do the form submission manually with jQuery Ajax method we could do that as well. We only need to do minor changes on the partial view and add the jQuery script. Below is the updated partial view:
@model DTO.ItemSellingDto

<div id="result">
@using (Html.BeginForm("CreateEditPartial", "ItemSellings", FormMethod.Post, new {id="ItemSellingForm"})) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ItemSelling</legend>
        <span style="color: red">@ViewBag.ErrorMessage</span>
        
        <div class="editor-label">
            @Html.LabelFor(model => model.Quantity)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Quantity)
            @Html.ValidationMessageFor(model => model.Quantity)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Price)
            @Html.ValidationMessageFor(model => model.Price)
        </div>

        . . .

        <div>
            <input id="btnCreateItemSelling" type="submit" value="Create" />
        </div>
    </fieldset>
}
</div>

<script type="text/javascript">
    $(function () {
        $('#ItemSellingForm').submit(function () {   // the form id is specified in Html.BeginForm method parameter
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (typeof result == 'object') {
                        $('#result').html('');  // this is to clear the update pane
                        addRow(result);
                    } else {
                        $('#result').html(result);  // display partial view again if input is not valid
                    }
                }
            });
            return false;  // don't forget this, otherwise the page will redirect
        });
    });
</script>
The other codes are still the same as shown here.

Tuesday, 16 July 2013

Using Partial View and AJAX for Validation - with Ajax.BeginForm

I would like to create a page that shows an update pane when a button is clicked. The pane should use Ajax so it will be displayed without page refresh. Below are how the screens will look like:



I also want some validation on the input fields on the update pane. However I prefer to have server validation so that all business rules can be put in one place. When the fields are submitted through Ajax, if there's a validation error the message should be shown. However if successful, the new record should be added to a listing table. All of this is done through Ajax so there will be no page refresh.


To be able to do this, first we need to create a Partial View that contains the input fields:
@model DTO.ItemSellingDto

<div id="result">
@using (Ajax.BeginForm(new AjaxOptions(){UpdateTargetId="result", HttpMethod="Post", 
    Url=Url.Action("CreateEditPartial","ItemSellings"), OnSuccess="addRow"})) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ItemSelling</legend>
        <span style="color: red">@ViewBag.ErrorMessage</span>
        
        <div class="editor-label">
            @Html.LabelFor(model => model.Quantity)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Quantity)
            @Html.ValidationMessageFor(model => model.Quantity)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Price)
            @Html.ValidationMessageFor(model => model.Price)
        </div>

        . . .

        <div>
            <input id="btnCreateItemSelling" type="submit" value="Create" />
        </div>
    </fieldset>
}
</div>
Note that in this case I use Ajax.BeginForm to help with the form submission. We could have used jQuery method $.ajax as well (I will write about this on the next post). Some of the AjaxOptions properties that I have used are:
- UpdateTargetId: this is the target element that will be updated after submission to the server side
- HttpMethod: POST or GET
- Url: this should point to the controller action to process the form
- OnSuccess: we can specify a javascript function to call after the form is successfully submitted.
There are some other options such as LoadingElementId, OnBegin, OnComplete and OnFailure. Please see this page for more details.
We also need a submit type element for the form. Also note that on the first line, we could use a model as well like a normal view.

To show this partial view when the button on the main view is clicked, add a placeholder somewhere on the main page and call the jQuery load function when the button is clicked.
// in this case the button id is 'btnAddItemSelling' 
// and I use a div with id 'itemSellings' for the placeholder
$("#btnAddItemSelling").click(function () {
 $("#itemSellings").load("@Url.Action("CreateEditPartial","ItemSellings")");
});
The url passed in the function parameter is the url used by GET controller action for displaying the partial view that we will create next.

Then we create the controller actions. We have two controller actions, one for displaying the partial view (GET) and the other for receiving the form data after submitted (POST). Note that the actions return partial view type when displaying and when the validation is failed. Also on line 9, we could pass a model as a parameter to the method from the Ajax form.
public ActionResult CreateEditPartial()
{
 // prepare and populate required data for the input fields
 // . . .

 return PartialView("CreateOrEdit");
}

[HttpPost]
public ActionResult CreateEditPartial(ItemSellingDto itemSellingDto)
{
 if (!ModelState.IsValid)
 {
  // prepare and populate required data for the input fields
  // . . .

  return PartialView("CreateOrEdit");
 }
 else
 {
  return Json(itemSellingDto);
 }
}
For the validation, in this case I just simply used Data Annotation but we could use other alternative such as a custom method, etc. I simply used   ModelState.IsValid   to check whether the inputs passed are fine. Then also put   @Html.ValidationMessageFor(...)   for each input field on the view. Note also that I enclosed the Ajax.BeginForm inside a div (please see line 3 and 34 on the partial view file above) and assign the Id to UpdateTargetId (one of the AjaxOptions properties) so that when input is not valid then the partial view content will be automatically put into the target element.

Next, include these two javascript references; jQuery and jQuery Unobtrusive Ajax on the main page. Do NOT put jQuery Unobtrusive Ajax on the partial page as this will cause the page to be submitted multiple times instead of once. Also write the javacript function that will be called when the validation from server side is successful. In this case, the code returns an object if validation is successful then the javascript function checks the data passed, if it is an object then add it to the listing table.



function addRow(response) {
 if(typeof response =='object')
 {
  // append object to table
  . . .
 }
}

Monday, 30 April 2012

Slides - a Slideshow Plugin for jQuery

When I was looking for a simple jQuery slideshow plugin, I came across to Slides (http://slidesjs.com). This plugin is simple to be implemented and seems to be highly customisable. It also supports either text or image content elements that can be easily set with html and css. In addition, it includes a pagination as well.

To get started, we need to include jQuery and the javascript library:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script>
<script src="js/slides.min.jquery.js" type="text/javascript" charset="utf-8"></script>
The file can be obtained from the plugin website http://slidesjs.com

Then prepare some basic html:
<div id='slides'>
    <div class="slides_container">
        <div>
            Content One
        </div>
        <div>
            Content Two
        </div>
        <div>
            Content Three
        </div>
    </div>
</div>
Note, the first div container's name can be anything, however the one inside it 'slides_container' should not be renamed. Then for each slide of the slideshow, we just need to create a separate 'div'. Inside each one of them, we can put any nested or more complicated html if we like.

Next, call the slides() function:


After that, we can put the desired html inside each 'div' and style them. We will also need to style the pagination later. An example can be found on http://slidesjs.com/examples/standard/

This is an example that I have:
<div id='slides'>
    <div class="slides_container">
        <div class="slide one">
            <div class='captionone'>
                <h1>Heading one</h1>
                <p>Content one 1 1 1 <a href='/page-one.aspx' class='more'>more</a></p>
            </div>
            <div class="bottomImages">
                <a class='imageone'></a>
                <a class='imagetwo'></a>
                <a class='imagethree'></a>
            </div>
        </div>
        <div class="slide two">
            <div class='captiontwo'>
                <h1>Heading twolt;/h1>
                <p>Content two 2 2 2 <a href='/page-two.aspx' class='more'>more</a></p>
            </div>
            <div class="bottomImages">
                <a class='imageone'></a>
                <a class='imagetwo'></a>
                <a class='imagethree'></a>
            </div>
        </div>
        <div class="slide three">
            <div class='captionthree'>
                <h1>Heading three</h1>
                <p>Content three 3 3 3 <a href='/page-three.aspx' class='more'>more</a></p>
            </div>
            <div class="bottomImages">
                <a class='imageone'></a>
                <a class='imagetwo'></a>
                <a class='imagethree'></a>
            </div>
        </div>
    </div>
 </div>
In my example, I have three slides with images background. On each slide there's a text element and three small images on the bottom that have hover styles as well.

Now for the pagination, the slideshow script generates a pagination underneath 'slides_container' div. Below is the html added by the script when we have three slides:
<ul class="pagination">
    <li class="current"><a href="#0">1</a> </li>
    <li class=""><a href="#1">2</a> </li>
    <li class=""><a href="#2">3</a> </li>
</ul>

We can style this as we like but we cannot change the html structures. Tips; if we would like to create a custom pagination inside/outside the slideshow div, we could use jQuery click event to make our custom pagination elements to do the same thing as the built in pagination when they are clicked. In the following example, I made the bottom images as my custom pagination:
$('#slides .imageone').click(function () {
    $("ul.pagination li:first-child a").click();
});
$('#slides .imagetwo').click(function () {
    $("ul.pagination li:nth-child(2) a").click();
});
$('#slides .imagethree').click(function () {
    $("ul.pagination li:last-child a").click();
});

There are also some parameters that can be set for the slides() function. For example:
$('#slides').slides({
    preload: true,
    preloadImage: '/images/loading.gif',
    play: 5000,
    pause: 2500,
    hoverPause: true,
    animationStart: function (current) {
        /* do something here */
    },
    animationComplete: function (current) {
        /* do something here*/
    },
    slidesLoaded: function () {
        /* do something here*/
    }
});
Please refer to the website for a list of parameters and their description.

Friday, 20 April 2012

Example of Using JQuery Validation Engine Plugin with ASP.NET Controls

JQuery validation engine is a jQuery plugin that provides easy to implement validation functionality for your html form. It also comes with nice styling and ample of built-in functions.

To start using this plugin, we need to include these scripts and css:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js" type="text/javascript"></script>
<script src="js/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css"/>
These files can be obtained from https://github.com/posabsolute/jQuery-Validation-Engine

There are many built in validation functions that can be put directly on an input control as its css classes; for example: required, custom, equals, min, max, etc... After the validations are placed, what we need to do is to instantiate the validation engine when the document is ready, ie:
$("#form.id").validationEngine();

We could also work with this plugin more manually by calling showPrompt or hide to show or hide the validation message when an input is invalid or corrected.

Below are some examples to validate some ASP.Net controls:

- Single Checkbox

var cb1= $('#<%=cbSingle1.ClientID %>:checked').val();
if (!cb1) {
    result = false;
    $('#<%=cbSingle1.ClientID %>').validationEngine('showPrompt', '* This field is required', null, null, true);
} else {
    $('#<%=cbSingle1.ClientID %>').validationEngine('hide');
}


- CheckBoxList

    one
    two
    three
    four

var cbl1Value = 0;
$('#<%=cblControl1.ClientID %> input[type=checkbox]:checked').each(function () {
    cbl1Value ++;
});
if (cbl1Value == 0) {
    // if nothing is selected
    result = false;
    $('.cblControl1Class').validationEngine('showPrompt', '* This field is required', null, 'topLeft', true);
} else {
    $('.cblControl1Class').validationEngine('hide');
}
Note that here we specify a css class on the control's CssClass attribute for showing the validation error message. We also pass 'topLeft' for the position, other possible values are 'topRight', 'bottomLeft', 'centerRight' and 'bottomRight'. We could also use X (horizontal) and Y (vertical) offsets from a position value in this format 'position_value:x,y', eg: 'topRight:30,-10'.


- RadioButtonList

    one
    two
    three
    four

var rbl1 = $('input[name=<%= rblControl1.ClientID %>]:checked').val();
if (!rbl1) {
    // if nothing is selected
    result = false;
    $('.rblControl1Class').validationEngine('showPrompt', '* This field is required', null, null, true);
} else {
    $('.rblControl1Class').validationEngine('hide');
}
Here we also use a css class to show the validation message.

For further information about this plugin, see http://posabsolute.github.com/jQuery-Validation-Engine
For more examples, see http://www.position-relative.net/creation/formValidator/

Friday, 30 March 2012

Client Side Custom Annotation Validation in ASP.NET MVC 3

On this post, we will see how to implement client side custom data annotation validation in ASP.NET MVC 3. I wrote about server side custom validation on my previous post.

There are a few steps that need to be done to implement client side custom validation:

1. Make our custom validation class (see my previous post for the codes example) inherits from IClientValidatable and implement its GetClientValidationRules method.
public class SumIntegers : ValidationAttribute, IClientValidatable
{
    . . .

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, 
          ControllerContext context)
    {
        ModelClientValidationRule rule = new ModelClientValidationRule();

        //specify a name for the custom validation
        rule.ValidationType = "sumintegers";

        //pass an error message to be used
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());

        //pass parameter(s) that need to be used when validating
        rule.ValidationParameters.Add("sum", _sum);

        yield return rule;
    }
}
To do this we need to add a reference to System.Web.Mvc namespace in the class file.

Below is the html generated from the ModelClientValidationRule properties set above.
<input type="text" value="" name="CSVInput" id="CSVInput" 
data-val-sumintegers-sum="20" 
data-val-sumintegers="custom error message for CSVInput" 
data-val="true" class="text-box single-line valid">
As we can see, the properties are put into data-val attributes. The attribute data-val-[validation_name] contains the error message, where [validation_name] is the ValidationType property's value we set above. Each passed parameter is put into data-val-[validation_name]-[parameter_name] attribute.


2. Write a jQuery validation adapter.
The adapter is used to retrieve the data-val attributes with their values and translate them into a format that jQuery validation can understand. So this adapter is helping us to easily implement our unobtrusive client side validation.

The adapter has several methods that we can use:
- addBool - creates an adapter for a validation rule that is 'on' or 'off', it requires no additional parameters
- addSingleVal- creates an adapter for a validation rule that needs to retrieve a single parameter value
- addMinMax - creates an adapter that maps to a set of validation rules, one that checks for a minimum value and the other checks for a maximum value
- add - used to create a custom adapter if we cannot use one of the methods above. We can use this if the adapter requires additional parameters or extra setup code.

In our case, addSingleVal is the best one to use.
// first parameter is the adapter name which should match with the value of ValidationType 
//    property of ModelClientValidationRule set on the server side
// second parameter is the parameter name added to ValidationParameters property of 
//    ModelClientValidationRule on the server side
$.validator.unobtrusive.adapters.addSingleVal("sumintegers", "sum");


3. Write the jQuery validator.
We do this through a method called addMethod that belongs to jQuery validator object.
// first parameter is the validator name which should match with the adapter name 
//    (which is also the same as the value of ValidationType)
// second parameter is the validation function to be invoked
$.validator.addMethod("sumintegers", 

  // the validation function's first parameter is the input value, second is the input element 
  //    and the third one is the validation parameter or an array of validation parameters passed
  function (inputValue, inputElement, sum) {

    var returnValue = true;
    if (inputValue) {
        var total = 0;

        try {
            $.each(inputValue.split(','), function () {
                total += parseInt(this);
            });
        }
        catch (err) {
            returnValue = false;
        }

        if (total != sum) {
            returnValue = false;
        }
    }
    return returnValue;

});

Say we put the scripts from step two and three in a single file called CustomScripts.js. Below is all the scripts that we have written:
/// <reference path="jquery-1.4.4.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

if ($.validator && $.validator.unobtrusive) {

    $.validator.unobtrusive.adapters.addSingleVal("sumintegers", "sum");

    $.validator.addMethod("sumintegers", function (inputValue, inputElement, sum) {
        var returnValue = true;
        if (inputValue) {
            var total = 0;

            try {
                $.each(inputValue.split(','), function () {
                    total += parseInt(this);
                });
            }
            catch (err) {
                returnValue = false;
            }

            if (total != sum) {
                returnValue = false;
            }
        }
        return returnValue;
    });

}
The first three lines are references put to have IntelliSense works in our codes. Make sure the paths are correct.


4. Finally, include jquery.validate, jquery.validate.unobtrusive and our custom scripts files on the page to render.
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/CustomScripts.js")"></script>


Tips: at the first time this validation will fire after the input lost focus but after that it will fire after each key press. This is the default behaviour of other built-in validators. If you are not happy with this and would like the validation to always fire only when the input lost focus then you need to add one of these scripts:
// if only for the specific input field
$(document).ready(function () {
    $("input#CSVInput").keyup(function () {
        return false;
    });
}

// or for all input fields
//    never put this inside document ready function
$.validator.setDefaults({
    onkeyup: false
})

Reference:
Professional ASP.NET MVC 3 - Jon Galloway, Phil Haack, Brad Wilson, K. Scott Allen

Monday, 5 December 2011

Calling Controller Action Method with HTTP GET Ajax Request

In this post, we will see how to do Ajax request using HTTP GET method with JSON in ASP.NET MVC3. HTTP GET method to retrieve data in JSON format should never be used for getting sensitive information, the POST method should be used instead. For more information of how to use the POST method, you can read my previous post; Ajax with jQuery and JSON in ASP.NET MVC 3 or Passing Object in JSON to Controller.

First we prepare our controller method that will respond to the Ajax call:
public JsonResult GetDetailsUsingHttpGet(int id)
{
    Team team = teamRepository.Find(id);
    var anonymousTeam = new { TeamId = team.TeamId, Name = team.Name };

    //'JsonRequestBehavior.AllowGet' must be set, otherwise we will get an error message '500 error'
    return Json(anonymousTeam, JsonRequestBehavior.AllowGet);
}
Since MVC version 2, a controller method that is responding to a GET request is not allowed to return JSON format data for security reason. We need to explicitly state that this operation is allowed by setting 'JsonRequestBehavior.AllowGet' in the returning Json() method.

Then our JavaScript codes:
$(document).ready(function () {
    $("#ajaxBtnGetOne").click(function (event) {
        $.ajax({
            type: "GET",
            url: "/Teams/GetDetailsUsingHttpGet/1",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: AjaxGETSucceeded,
            error: AjaxFailed
        });
    });  
});
function AjaxGETSucceeded(objdata) {
    alert('success');
    alert(objdata.TeamId + ' - ' + objdata.Name);
    $('#ajaxDiv').html(objdata.TeamId + ' - ' + objdata.Name);
}
function AjaxFailed(result) {
    alert('an error has occured: ' + result.status + ' ' + result.statusText);
    alert(result.responseText);
}
Note that in the Ajax function we pass a parameter through its 'url' setting; in this example is '1' that will be passed as an 'id' parameter.

Monday, 28 November 2011

Passing Object in JSON to Controller

In this post, we will see how to pass object(s) in JSON from a jQuery Ajax function to a controller method in ASP.NET MVC 3. For more detailed explanation about the jQuery function and receiver controller method, you may want to see my previous post.

First we prepare our class which structure will be similar as the structure of the object(s) in JSON that is going to be passed. This class will also be the data type of the object(s) received by the receiver method through its parameter:
public class TeamViewModel
{
    public int TeamId { get; set; }
    public string Name { get; set; }
}

Then our JavaScript codes (jQuery version used at the time of writing is 1.5.1):
$(document).ready(function () { 
    //pass an object 
    $("#ajaxBtnPostTwo").click(function (event) {
        $.ajax({
            type: "POST",
            url: "/Teams/ProcessObjectUsingHttpPost",
            data: "{ 'TeamId':'10', 'Name':'TopTeam' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: ObjectWithAjaxSucceeded,
            error: AjaxFailed
        });
    });

    //pass a collection of objects
    $("#ajaxBtnPostThree").click(function (event) {
        var teamlist = [ { TeamId: 5, Name: 'Team Five'},
                            { TeamId: 6, Name: 'Team 6'},
                            { TeamId: 7, Name: 'Team seven'} ]

        $.ajax({
            type: "POST",
            url: "/Teams/ProcessListObjectsUsingHttpPost",
            data: JSON.stringify(teamlist),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: ObjectWithAjaxSucceeded,
            error: AjaxFailed
        });
    });
});

function ObjectWithAjaxSucceeded(data) {
    alert('success');
    //write content to a div
    $('#ajaxDiv').html(data);
}
function AjaxFailed(result) {
    alert('an error has occured: ' + result.status + ' ' + result.statusText);
    alert(result.responseText);
}
Note that the first ajax function is passing an object while the second one is passing a collection of objects. On the first method, the object is specified directly in the JSON string. While on the second method, JSON.stringify() method is used to convert the JavaScript objects into JSON string.

Finally, our controller methods:
[AcceptVerbsAttribute(HttpVerbs.Post)]
public JsonResult ProcessObjectUsingHttpPost(TeamViewModel team)
{
    return Json(String.Format("{0} -processed- <br/> {1} -processed-",
                            team.TeamId, team.Name));
}

[AcceptVerbsAttribute(HttpVerbs.Post)]
public JsonResult ProcessListObjectsUsingHttpPost(List<TeamViewModel> teams)
{
    StringBuilder sb = new StringBuilder();
    foreach (TeamViewModel team in teams)
    {
        sb.AppendFormat("{0} -processed- , {1} -processed <br />", team.TeamId, team.Name);
    }
    return Json(sb.ToString());
}
The first one receives a single object while the second one receives a collection of objects. The framework automatically serialize the JSON data into the data type (class) that we have specified above; ie. TeamViewModel.

On the next post we will see how to do Ajax call with HTTP GET method.

Monday, 21 November 2011

Ajax with jQuery and JSON in ASP.NET MVC 3

In this article, we'll see how to do Ajax request using HTTP POST method in ASP.NET MVC 3. The recent MVC framework allows this to be done easily.

First we prepare our html controls.
<input id="ajaxBtnPostOne" value="Ajax Button Post 1" param="1" type="button" />
<div id='ajaxDiv'></div>

Then the javascript codes. Make sure you have jQuery library in the application. In this article, I use jQuery 1.5.1.
$(document).ready(function () {
    $("#ajaxBtnPostOne").click(function (event) {
        $.ajax({
            type: "POST",
            url: "/Teams/GetDetailsUsingHttpPost", 
            data: "{ 'id':'" + $('#ajaxBtnPostOne').attr('param') + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: AjaxSucceeded,
            error: AjaxFailed
        });
    });
});

function AjaxSucceeded(data) {
    alert('success');
    //write content to a div
    $('#ajaxDiv').html(data);
}

function AjaxFailed(result) {
    alert('an error has occured: ' + result.status + ' ' + result.statusText);
    alert(result.responseText);
}
Note that we use jQuery function $.ajax() to bind to the 'on clicked' event of the html button we have above.
The settings on this method:
- type: we want use HTTP POST.
- url: this is the url where the Ajax call will be posted to. In this case is the location of the server side method 'GetDetailsUsingHttpPost' that we are going to create below.
- data: this is the data that will be passed to the method.
- dataType: we want to use JSON in this case.
- success: what to do when the Ajax call is returned successfully, in this case we execute a method.
- error: what to do if an error occurred, in this case we execute a method.

Then we have the server side receiver method. In MVC, we can simply use a controller method to handle an Ajax call. No extra configuration is needed.
[AcceptVerbsAttribute(HttpVerbs.Post)]
public JsonResult GetDetailsUsingHttpPost(int id)
{
    Team team = teamRepository.Find(id);
    return Json("Team Name = " + team.Name);
}
Note that '[AcceptVerbsAttribute(HttpVerbs.Post)]' attribute is used so that the method will only respond to a POST method. When Ajax call is used with JSON to query sensitive information, it is recommended to use POST method. Please see http://haacked.com/archive/2009/06/25/json-hijacking.aspx for more details.

Also notice that the method accept an integer parameter however the passed data is a string; the framework does the conversion automatically. Note that the variable name ('id') used in the 'data' setting of the javascript function is the same as the one accepted by the method.

To return JSON data, we just need to put the data to be returned inside Json() method and specify the controller method's return type as JsonResult.

Say now we want to return an object instead of a string. To do this, we can simply use an anonymous type or a class. If we choose to use a class then prepare our class, eg. TeamViewModel:
public class TeamViewModel
{
    public int TeamId { get; set; }
    public string Name { get; set; }
}
No extra configuration is needed to return an anonymous type or a class' object to the Ajax call. Here is our modified controller method:
/*modified to return an object instead of string data*/
[AcceptVerbsAttribute(HttpVerbs.Post)]
public JsonResult GetDetailsUsingHttpPost(int id)
{
    Team team = teamRepository.Find(id);
    TeamViewModel teamVM = new TeamViewModel();
    teamVM.TeamId = team.TeamId;
    teamVM.Name = team.Name;
    return Json(teamVM);

    // we could also have used an anonymous type instead
    //var anonymousTeam = new { TeamId = team.TeamId, Name = team.Name, City = "sydney" };
    //return Json(anonymousTeam);
}
We need to change the js function that is called when the Ajax call is successful:
function AjaxSucceeded(objdata) {
    alert('success');
    alert(objdata.TeamId + ' - ' + objdata.Name);
    $('#ajaxDiv').html(objdata.TeamId + ' - ' + objdata.Name);
}
Notice that the received object has similar structure as the returned object's type from the controller method; ie. it has 'TeamId' and 'Name' members. It also preserve the case sensitivity of the properties; if we use small case letters 'objdata.teamid' instead of 'objdata.TeamId', this will be rendered as 'undefined'.

On the next post, we will see how to pass object(s) in the Ajax function.