HTML and CSS Reference
In-Depth Information
Using the jQuery $.ajax() Method in an MVC Application
Working with MVC applications and calling server-side code from jQuery is simple. You don't need to
create a separate service (of course, you can if you so wish). Instead, you can encapsulate the code in a
controller action method. For example, Listing 2-17 shows the
Convert()
action method that encapsulates
the temperature-conversion logic.
Listing 2-17.
Convert()
Action Method in an MVC Controller
public JsonResult Convert(TemperatureData t)
{
if (t.Unit == "C")
{
t.Value = (t.Value * 1.8m) + 32;
t.Unit = "F";
}
else
{
t.Value = (t.Value - 32) / 1.8m;
t.Unit = "C";
}
return Json(t);
}
As you can see, the
Convert()
action method accepts a parameter of type
TemperatureData
and returns
a
JsonResult
. The
JsonResult
class wraps a return value in JSON format. Notice how the
JsonResult
object
is returned using ASP.NET MVC's
Json()
method; this method accepts data to be returned and converts it
into JSON format.
You can call the
Convert()
action method from the client side by writing the jQuery code shown in
Listing 2-18.
Listing 2-18.
Calling a Controller Action Method Through
$.ajax()
()
$(document).ready(function () {
$("#Button1").click(function () {
url = "/Home/Convert";
data = '{ Value: "' + $("#Text1").val() + '", Unit: "' + $("#Select1").val() + '" }';
$.ajax({
type: "POST",
url: url,
data:data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
})
});
});
function OnSuccess(results) {
alert("Converted Temperature : " + results.Value + " " + results.Unit);
}