I’m trying to make an AJAX call to a model that I have in my MVC project. I keep receiving the following error:
POST foobar/GetDate 405 (Method Not Allowed)
(Where ‘foobar’ is my localhost:port format for the MVC project.)
I haven’t played around with routing in the project yet, as I’m not sure what a route to a script should look like. I know how to properly route views at this point. Here are some code snippets:
In my MVC Project, I have a Model with the following method:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
In my Index.aspx file, I have this code:
<button class="getDate">Get Date!</button>
<div class="dateContainer">Empty</div>
And in my script.js file, I have this code:
$.ajax({
type: "POST",
url: "GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace text in dateContainer with string from GetDate method
$(".dateContainer").text(msg.d);
},
complete: function (jqHXR, textStatus) {
// Replace text in dateContainer with textStatus
if (textStatus != 'success') {
$(".dateContainer").text(textStatus);
}
},
});
My end goal is to send XML data to my method in the C# model, then parse and save the XML document.
Right now, I’ll settle on trying to link up the AJAX request in jQuery to the C# method I have. I’m positive it has something to do with routing and syntax.
Thanks in advance!
Why do you have an
[WebMethod]method in an MVC Project ?In MVC, you can have
actionmethods in yourcontrollers. You can call this from ajax as wellYou can call it from your javascript like this (with jQuery)
If you are doing a
POSTcall to the method, make sure to decorate your action method with POST attribute.You can even return JSON from your action method to your ajax call’s callback function. There is a
JSONmethod inController(the base class of our WebController) class to do this.