Tuesday, 28 February 2012

Asp.net mvc using JsonResult

Json has become one of the most popular form of data interchange method and being tightly integrated in the mvc framework makes it very easy to use. I will be demonstratating a very usefull technique of passing a response in an Ajax style using JsonResult (It is a class that is used in mvc framework to pass a json formatted content to the response).

Model
    public class Users
    {
       public int UserId { get; set; }
       public string UserName { get; set; }
    }

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

    public JsonResult GetUsers()
    {
       List<Users> users = new List<Users>()
                           {
                           new Users
                           {
                           UserId =1, UserName ="kaunain"
                           }};
       return this.Json(users,JsonRequestBehavior.AllowGet);
    }

View
<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        $.getJSON("/Home/GetUsers", null, function (data) {
            $.each(data, function (index, users) {
                    $("p").text(users.UserName);
            });
        });
    });
</script>


Updated view for multiple users
<script type="text/javascript" language="javascript">   
   
       $(document).ready(function () {
        $.getJSON("/Home/GetUsers", function (data) {
            var items = [];

            $.each(data, function (key, users) {
                items.push('<li id="' + users.UserId + '">' + users.UserName + '</li>');
            });

                    $('<ul/>', {
                        'class': 'Users-list',
                        html: items.join('')
                    }).appendTo('p');
               });
       });
    
 
</script>

Lastly specify Home/GetUsers route in global.asax.

No comments:

Post a Comment