Pages

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)
}

No comments:

Post a Comment