Pages

Showing posts with label Ajax in MVC4. Show all posts
Showing posts with label Ajax 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);
            }
        });


Tuesday, 11 March 2014

Calling Controller Action on HTML button click using Ajax MVC4

             Following Code is used to call controller action on html button click via ajax call. Advantage of using ajax is that all task get performed without reloading the whole page. Ajax is used to reload only part of the page.

/*Razer code*/
@Html.TextBox("txt",null,new{@id="txtName"})
<input type="button" id="btnAdd" value="Add" />
/* Javascript Code*/
$('#btnAdd').click(function(){
   $.ajax({
//data contains the object which you are passing to controller action
data: { value=$("#txtName").val()},
         url: '@Url.Action("Home","Index")',
//type may be POST or GET
         type: "GET",
//datatype depends on your requirements
        dataType: "JSON"
//success executes on successful call
success:function(data)
{
//Write your  logic on  successful execution of ajax here
},
error:fuction(){
alert("error in loading data");
}
});
});
/*
Name of ajax passed object to the controller action and Name of Controller Action Variable who is receiving the object passed from ajax is same. Always receive ajax object form data in string
*/
/*Controller Action*/
public ActionResult Index(string value)
{
//Write your business logic here and return json result
return JSON(result, JsonRequestBehavior.AllowGet)
}