You could put this in a separate javascript file that could be referenced from your view. For example:
<script type="text/javascript" src="~/scripts/myscript.js"></script>
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:
<script type="text/javascript">
var myActionUrl = '@Url.Action("SomeAction", "SomeController")';
</script>
<script type="text/javascript" src="~/scripts/myscript.js"></script>
and then in your javascript file use this variable:
$.ajax({
type : "GET",
dataType : "json",
url : myActionUrl,
success: function(data) {
alert(data);
}
});