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 main page.
In simple HTML,JavaScript I using ajax to GET/POST JSON data
<script>
$.ajax({
type : "GET",
dataType : "json",
url : "www.site.com",
success: function(data){
alert(data);
}
});
</script>
I created MVC 4 project, where should I call the jQuery $.ajax command to get data and display it ?
Do I have to call it in the View? and with the jQuery syntax?
I’ll be happy to see any example
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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);
}
});
Method 2
Try the following
Controller
public class JsonController : Controller
{
public ActionResult Simple()
{
return View();
}
public JsonResult SimpleJson()
{
var persons = new List<Person>
{
new Person{Id=1, FirstName="Harry", LastName="Potter"},
new Person{Id=1, FirstName="James", LastName="Potter"}
};
return Json(persons, JsonRequestBehavior.AllowGet);
}
}
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
In simple.aspx view
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Simple</title>
<script src="../../Scripts/jquery-2.0.3.intellisense.js"></script>
<script src="../../Scripts/jquery-2.0.3.js"></script>
<script src="../../Scripts/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#FillButton').click(function () {
$.getJSON("/Json/SimpleJson", null, function (data) {
var div = $('#ajaxDiv');
$.each(data, function (i, item) {
div.append("<br /><br />First Name: " + item.FirstName);
div.append("<br />Last Name: " + item.LastName);
});
});
});
});
</script>
<div>
<div id="ajaxDiv">
</div>
<input id="FillButton" type="button" value="Get Persons" />
</div>
Method 3
You have to make ajax call in view, just call MVC url which return json data and operate on that data.
<script>
$.ajax({
type : "GET",
dataType : "json",
url : "www.site.com/{controller}/{action}/{id}",
success: function(data){
alert(data);
}
});
</script>
pass the Controller, Action and Id part whichever is applicable in the ajax call.
Hope this will help you
Method 4
You can call ajax function from your view, like below.
var oModel = {};
oModel.Id = $('#hiddenid').val();
oModel.Name = $('#hiddenName').val();;
$.ajax({
url: "/SomeController/SomeActionMethod",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(oModel),
}).done(function (data) {
alert(JSON.stringify(data));
});
and have method named “SomeActionMethod” in your controller like below,
[HttpGet]
public ActionResult SomeActionMethod(oModel oVarModel)
{
//Do some stuff
return someReturn;
}
Hope this helps.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0