Monday, June 11, 2012

Using JSON response in JQUERY in MVC

I've found that using JSON in MVC is very handy and useful , Consider you have a template of a usercontrol/control and when an event triggers on the page you want to load the new data in your control, there are many ways to do it , one of the good ways is returns the usercontrol/control with new data completely on the page and add it again and also remove the previous one, but a question is when you already have the userontrol/control on the page and only difference is showing new data on it do you think a faster is just to load the new data and bind it into the usercontrol/control? for sure yes it is.

loading the data and bind it to your control can be handle in different ways as well , but I like JSON  format better.

Let's start calling a controller to return a simple int[] but in JSON format and see how it works.

Consider we have a method in our any controller such as PersonController to return a list of person and use it in the VIEW.

public class Person
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int PersonID { get; set; }

 public ActionResult GetPeople(string CountryCode)
            List<Person> people=new List<Person>();
            for (int i = 0; i < 10; i++)
                people.Add(new Person() { FirstName = string.Format("Name-{0}",i),LastName =  string.Format("Family-{0}",i),PersonID = i});

            //creating a JSON response format , so you can see the "res" object
            JsonResult res = Json(people);
            return res;

Now  you have an action which returns a list of person in JSON format, the only thing is call this action via JQUERY and read it and bind it to your object, since my focuse on this exercise is just to read JSON format data with JQUERY , I'm not talking about the specific control you may need.

Consider an event in your page triggers(like clicking on btnRefresh) and you want to call GetPeople action , this Action may need some parameters like CountryCode
NOTE: when you are calling $.post you are able to specify the format of the data you expect after defining the action parameter , here for this example sine I know the action returns JSON data format, so in $.post we should specify the 'json' as data format of the response.

JQuery in your VIEW

    $(btnRefresh).unbind("click").click(function() {    

        $.post('Person\GetPeople', { CountryCode: 'en-US'}, function(data) {
           //data is people
            $(data).each(function(index, person) {
                //alerting people info or you can repopulate your specific control based on this data
                alert('FName:' + person.FirstName+ ', LName:'+person.LastName+', PersonID:'+person.PersonID.toString() );

      }, 'json');


No comments:

Post a Comment

Thank you for sharing your knowledge and experiences with this weblog.