Basic Call
Let’s just make a call to the server to get a single value:
We’ll call this JS function, for example, using a button like <input type=”button” onclick=”SingleCall();”/>:
function SingleCall() { var url = '@Url.Action("AJAXRequest", "AJAX")'; jQuery.ajax({ url: url, success: function (data) { console.log('Returned data is: ' + data); //Note: Remember though data is an int it's returned as a string, // so if you want to get it as int you need to use parseInt() } }); }
And have this simple Controller (I’ve created a Controller called AJAX, but you can use any Controller for these requests).
public partial class AJAXController : Controller { public virtual int AJAXRequest() { return 5; } }
Adding parameters to our call
The easiest way is to add them to the url, using GET:
function CallWithParamsOnGet() { var url = '@Url.Action("AJAXRequest", "AJAX")' + '?param1=' + 5 + "¶m2=" + 3; jQuery.ajax({ url: url, success: function (data) { console.log('Returned data is: ' + data); } }); }
Controller Action:
public virtual int AJAXRequest(int param1, int param2) { return (param1 + param2); }
Sending parameters in a Post
Script:
function CallWithParamsOnPost() { var url = '@Url.Action("AJAXRequest", "AJAX")'; jQuery.ajax({ url: url, type: 'POST', data: { 'param1': 5, 'param2': 3, 'param3': 'someText' }, success: function (data) { console.log('Returned data is: ' + data); } }); }
Controller Action:
public virtual int AJAXRequest(int param1, int param2, string param3) { return (param1 + param2); }
Notice I’ve added a third parameter that I’m not using, it’s just to show that you can send integers, strings, objects (you need to serialize them, see below), etc. on a post.
Sending the form/model
Now we are getting into a more interesting and MVC connected request. We can serialize the form and send it in a post. As MVC works with models and the form should be implementing some model, this will reduce your work a lot.
I’ve had to add this little Model:
public class MyTestingModel { public int Param1 { get; set; } public int Param2 { get; set; } public MyTestingModel() { //def values to help testing Param1 = 5; Param2 = 3; } }
Then I prepare the Controller like this:
public partial class AJAXController : Controller { public virtual int AJAXRequest(MyTestingModel model) { return (model.Param1 + model.Param2); } public virtual ActionResult Test() { var m = new MyTestingModel(); return View(m); } }
And this is how we send it from the View:
@model MyNamespace.MyTestingModel @{ ViewBag.Title = "Testing"; } @using (Html.BeginForm("AJAXRequest", "AJAX", FormMethod.Post)) { @Html.TextBoxFor(m => m.Param1) @Html.TextBoxFor(m => m.Param2) <input type="button" onclick="CallSendingForm(this);"/> } @* /End form *@ <script type="text/javascript"> function CallSendingForm(caller) { var url = '@Url.Action("AJAXRequest", "AJAX")'; // My button is inside the form, if yours isn't just look for it your own way. var myForm = $(caller).parents("form"); var data = $(myForm).serialize(); jQuery.ajax({ url: url, type: 'POST', data: data, success: function (data) { console.log('Returned data is: ' + data); } }); } </script>
Notice I’m not using a submit button but a simple “input type=button” as we don’t want the post to be sent on a full page request but via AJAX.
Sorry about the 3 variables using the same name “data”, just notice they are not the same variable as they are in different scopes. First data variable is declared under the function, second one is a property belonging to the Ajax object, third data variable is a parameter inside the event success. The three of them have different scopes so they don’t collide, but you can use different names if that worries you. If that’s confusing you, look at this:
<script type="text/javascript"> function CallSendingForm(caller) { var url = '@Url.Action("AJAXRequest", "AJAX")'; var myForm = $(caller).parents("form"); var myDataVariable = $(myForm).serialize(); jQuery.ajax({ url: url, type: 'POST', data: myDataVariable, success: function (dataParameter) { console.log('Returned data is: ' + dataParameter); } }); } </script>
Retrieving our model
Now that we have seen all the ways to make a request, let’s see how to get not just an integer, but something more complex, like our Model back:
First of all, let’s make some changes to our Model/Controller so that we’ll return a JSON string this time but I’m also adding another property to the Model to play with it:
public partial class AJAXController : Controller { public virtual ActionResult Test() { var m = new MyTestingModel(); return View(m); } public virtual JsonResult AJAXRequest(MyTestingModel model) { model.Sum = (model.Param1 + model.Param2); return Json(model); } } public class MyTestingModel { public int Param1 { get; set; } public int Param2 { get; set; } public int Sum { get; set; } public MyTestingModel() { //def values to help testing Param1 = 5; Param2 = 3; Sum = Param1 + Param2; } }
Now, we can retrieve a JSON (which is just a string in a format that allows us to map/unmap objects) accessing the object properties directly:
function CallSendingForm(caller) { var url = '@Url.Action("AJAXRequest", "AJAX")'; var myForm = $(caller).parents("form"); var data = $(myForm).serialize(); jQuery.ajax({ url: url, type: 'POST', data: data, success: function (data) { console.log('The sum for ' + data.Param1 + ' and ' + data.Param2 + ' is: ' + data.Sum); } }); }
Retrieving a Dictionary
A good way of refilling dynamic combos:
function CallSendingForm(caller) { var url = '@Url.Action("AJAXRequest", "AJAX")'; var myForm = $(caller).parents("form"); var data = $(myForm).serialize(); jQuery.ajax({ url: url, type: 'POST', data: data, datatype: 'JSON', success: function (data) { jQuery.each(data, function (key, value) { console.log('key: ' + key + ' | value: ' + value); }); } }); }
Notice I’ve set the datatype:JSON as a way of telling jQuery I’m going to get that, so jQuery will retrieve the json and convert it automatically.
The Controller Action changed jsut a bit to create a Dictionary:
public virtual JsonResult AJAXRequest(MyTestingModel model) { var dic = new Dictionary<string, string>(); for (int i = 0; i < 5; i++) { dic.Add(i.ToString(), (model.Param1 * i).ToString()); } return Json(dic); }
Retrieving a List<object>
As we can play with Json we can create objects, list of objects, sub objects inside those objects, … let’s see just an example of how to retrieve a list of objects to play with in Javascript using jQuery:
First of all, the Action returning a list of our little Model:
public virtual JsonResult AJAXRequest(MyTestingModel model) { var list = new List<MyTestingModel>(); for (int i = 0; i < 5; i++) { var m = new MyTestingModel(); m.Param1 = i; m.Param2 = i*i; list.Add(m); } return Json(list); }
Now, as we want to use the same properties that model has, we need to replicate the object declaration in javascript, so let’s do this:
function MyTestingModel(data) { this.Param1 = data.Param1; this.Param2 = data.Param2; }
Then we map it using jQuery.map():
function CallSendingForm(caller) { var url = '@Url.Action("AJAXRequest", "AJAX")'; var myForm = $(caller).parents("form"); var data = $(myForm).serialize(); jQuery.ajax({ url: url, type: 'POST', data: data, datatype: 'JSON', success: function (data) { var mappedModels = $.map(data, function (item) { return new MyTestingModel(item); }); $(mappedModels).each(function () { console.log('p1: ' + this.Param1 + ' | p2: ' + this.Param2); }); } }); }
Full view of the script:
<script type="text/javascript"> function CallSendingForm(caller) { var url = '@Url.Action("AJAXRequest", "AJAX")'; var myForm = $(caller).parents("form"); var data = $(myForm).serialize(); jQuery.ajax({ url: url, type: 'POST', data: data, datatype: 'JSON', success: function (data) { var mappedModels = $.map(data, function (item) { return new MyTestingModel(item); }); $(mappedModels).each(function () { console.log('p1: ' + this.Param1 + ' | p2: ' + this.Param2); }); } }); } function MyTestingModel(data) { this.Param1 = data.Param1; this.Param2 = data.Param2; } </script>
very useful, there ajax operation i am searching long back but you guyz solve the problem. Thank you so much.
Thank You Very much. All my questions answered in a single page. Awesome (y)