Wednesday, April 10, 2013

JQuery & MVC2 Example


Here i give an example for  binding the state to dropdown list  based on the country   by mvc & jquery

First we need to create the Controller called "Country"  & add a action called state .  and then i have given here  json  data to return in that action.



      public JsonResult State(string Country)
        {
            //items is your list what ever how you get it
            List State = new List();
            if (Country == "India")
            {
             
                State.Add("TN");
                State.Add("KA");
            }
            else if (Country == "US")
            {
                State.Add("CA");
                State.Add("NY");
            }

            var stateList = State;
            return Json(stateList, JsonRequestBehavior.AllowGet);
         
        }




now we talk about jquery part .   by using $.ajax() call ,  we need to post the request to Country controller for action  "State".  So url should be '/Country/State'.  we need to define the datatype  to json.  the parameter part should be done with data . if the ajax called request successfully , then sucess block gets executed .  we add anonymous function to bind the data as following one.  meanwhile if any exception are thrown,  ajax's error handle function added


 $(document).ready(function () {

          $.ajax({
              type: "POST",
              url: "/Country/State",
              datatype: 'json',
              data: {Country:'US'},
              success: function (data) {

                  $('#mes').html(data);
                  var items = '';
                  for (var i = 0; i < data.length; i++) {
                      items = data[i];
                      $("#Select1").append('');                  
                  }

              }
                ,
              error: function (request, status, error) {
                  alert(error);
              }
          });


      });


Regards
Guna seakran

No comments:

Post a Comment