In asp.net web form application, if we need ajax service, we will need to create wcf services on server side to serve ajax calls, while in MVC web application, no wcf is needed, a controller will do.
Here are two examples (GET and POST) of how to use ajax in mvc application
Http Get example: ajax consumer in view
<script type="text/javascript">
var user = {
'id': 1
};
$.get(
'home/getUser',
user,
function (data) {
alert(data.name);
}
);
</script>
Http Get example: ajax server in home controller
public class HomeController : Controller
{
// data GET service
public JsonResult getUser(int id)
{
User user = db.Users.where(u=>u.id==id)
return Json(user,JsonRequestBehavior.AllowGet); }
}
A few points:
Controller must return JsonResult rather than ActionResult as a normal controller does as we would want the data to be returnd as json data, and it does not have a ‘d’ wrapper
JsonRequestBehavior.AllowGet must be set in Json()call, otherwise you will get:
500 internal server error with message like
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet
You only need to set this parameter for GET and returning JSON array to avoid JSON hijacking, no need for POST requests.
Http POST example: ajax consumer in view
<script type="text/javascript">
var user={
'name':’TheUser’,
'age':30
};
$.post(
'home/SaveUser',
user,
function (data) {
if (data === true) {
alert('User is saved');
}
else {
alert('Failed to save the user');
}
},
'json'
);
</script>
Http POST example: ajax server in home controller
public class HomeController : Controller
{
// data POST service
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult SaveUser (string name, int age)
{
return Json(true); }
}
A few points:
Have to decorate the controller with ‘POST’
Datatype in $.post in example is set to json, but it is not necessary to be so, if you just pass data in fields rather than in complex object. When it is not set to json it will use application/x-www-form-urlencoded as a way to pass data in standard post.
Summary:
In asp.net MVC you can use controller as ajax server without having to use wcf, compared with wcf, no configuration is needed
HostForLIFE.eu ASP.NET MVC Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.