Reputation: 4209
Trying my way on a little bit of JSON here in my asp.net mvc project. I have the following View:
<asp:Content ID="Content3" ContentPlaceHolderID="NavigationPlaceholder" runat="server">
<script type="text/javascript">
$(document).ready(function () {
alert('loaded');
$.getJSON('/Students/LoadYearRoot', null, function (data, textStatus) {
alert('test');
});
});
</script>
</asp:Content>
and the following controller (Please note that i commented out my database call and is just trying with strings.:
public JsonResult LoadYearRoot()
{
GWSSchool school = SchoolHelper.GetSchool();
//List<GWSYear> years = yearRepository.GetAll(school.Id);
List<string> strings = new List<string>() { "first", "second", "third" };
JsonResult result = this.Json(strings);
return result;
}
Observing the view i get my first alert, showing "loaded", but then it stops, and i never get into the callback function, i tested that i hit the controller using a breakpoint, so the result seems right.
Any ideas, all examples i found on the web is exactly like this, what am i missing?
Upvotes: 1
Views: 507
Reputation: 1038830
By default JSON is not allowed for GET verbs which is what you are using for your AJAX request ($.getJSON
). In order to enable it you could pass the JsonRequestBehavior.AllowGet
value to the Json method in your controller action:
JsonResult result = this.Json(strings, JsonRequestBehavior.AllowGet);
And next time when one of your AJAX requests doesn't work instead of directly posting a question on StackOverflow, simply open your javascript debugging tool in your favorite browser (FireBug in FireFox, Chrome developer tools in Google Chrome, I don't know what in IE - in fact don't use IE to develop a web application - my definition of IE is the following: a Windows application developed by Microsoft used to download a web browser when you reinstall your operating system) and look at the Network
tab. There you will see your AJAX request and response from the server. You will also see the HTTP status code returned by the server. Simply expand the response and read the error message the server sent you. In this very specific case it will even tell you how to solve the problem.
Another sidenote about your code. Absolutely never hardcode an url like this in an ASP.NET MVC application:
$.getJSON('/Students/LoadYearRoot', ...
Always, and absolutely always use url helpers when dealing with urls in an ASP.NET MVC application, like this:
$.getJSON('@Url.Action("LoadYearRoot", "Students")', ...
The reason for this is that your code is no longer dependent on the routes you configured in Global.asax and in addition to that it will even work when you deploy your application in a virtual directory in IIS in which case you need to prepend the application name.
Upvotes: 3