I started to learn ASP.NET MVC 4
, did some small stuff...
In my index page I want to get JSON
file with some data and display it on the mai
You could put this in a separate javascript file that could be referenced from your view. For example:
and inside the script make the AJAX call:
$.ajax({
type : "GET",
dataType : "json",
url : "/SomeController/SomeAction",
success: function(data) {
alert(data);
}
});
The controller action you are invoking should obviously return a JsonResult:
public ActionResult SomeAction()
{
var model = new
{
Foo = "Bar",
}
return Json(model, JsonRequestBehavior.AllowGet);
}
There's a further improvement to be made to this javascript. You may notice the hardcoded url to the controller action:
url : "/SomeController/SomeAction",
This is not good because the pattern of your urls is governed by routes and if those routes change you will also have to modify your javascript. Also if you deploy your application inside a virtual directory in IIS, this path no longer will take into account the virtual directory name.
For this reason it is always recommended to use url helpers to generate the url to a controller action. For example you could store this into a global javascript variable in the view:
and then in your javascript file use this variable:
$.ajax({
type : "GET",
dataType : "json",
url : myActionUrl,
success: function(data) {
alert(data);
}
});