I have the following code in a razor .cshtml file. Clicking a button should fire an ajax GET request which should pop up an alert with whatever data the server returned. (the JS below is within document.ready)
$("#ajax-form").click(function () {
alert("event fired");
$.ajax({
url: '/apartments/getData',
type: 'GET',
dataType: "text",
success: function (data) {
alert(data);
},
error: function (data) {
alert("Error");
}
});
});
And the view code:
<div class="row">
<form id="ajax-form">
<input type="submit"/>
</form>
</div>
Here is the controller code:
[HttpGet]
public string getData()
{
return "Some dummy data here";
}
The event is definitely firing but the request fails (the error function fires). I could not get this to work with $.post or $.get either. Also typing localhost:54637/apartments/getData opens a page with "Some dummy data here".
Any ideas? Is there some particular way an asp.net MVC route must be settup to respond to an AJAX request?