Pages

Showing posts with label Controller action returns JSON result in MVC4. Show all posts
Showing posts with label Controller action returns JSON result in MVC4. Show all posts

Wednesday, 12 March 2014

Retriving JSON result on Ajax call in MVC4

Following code returns all the states comes under given country. Here country is passed through ajax call.

/*Following action receives "country" as argument from Ajax call and retrieves all the states*/

 public JsonResult GetStates(string country)
        {

            using (AMSEntities Context = new AMSEntities())
            {
                int id = Convert.ToInt32(country);
                List<AMSState> conti = Context.AMSStates.Where(x => x.CountryId == id).ToList();
                var query = (from x in conti select new { Id = x.StateId, Name = x.StateName });
                return Json(query, JsonRequestBehavior.AllowGet);
            }
        }

/*Ajax call for above action in MVC4 "#state" is the Id dropdown list who is showing the result*/

 $("#state").prop("disabled", true);
        $("#country").change(function () {
            if ($("#country").val() != "Select Country") {
                var options = {};
                options.url = '@Url.Action("GetStates", "Agreement")';
                options.type = "POST";
                options.data = JSON.stringify({ country: $("#country").val() });
                options.dataType = "json";
                options.contentType = "application/json";
                options.success = function (state) {
                    $("#state").empty();
                    for (var i = 0; i < state.length; i++) {
                        $("#state").append("<option value=" + state[i].Id + ">" + state[i].Name + "</option>");
                    }
                    $("#state").prop("disabled", false);
                };
                options.error = function () { alert("Error retrieving states!"); };
                $.ajax(options);
            }
            else {
                $("#state").empty();
                $("#state").prop("disabled", true);
            }
        });