I know there's a lot of questions for this topic, but I can't seem to get it to work even after trying them out. I'm trying to call a controller method that takes in a parameter and returns a string with that parameter, but it's not working. Also, I am executing an ajax GET call to do this.
My controller method:
public class TestController: Controller
{
[HttpGet]
public string GetString(string word)
{
return "Hello from Get" + word;
}
}
My javascript code
testFunc();
function testFunc() {
var word = "yay";
$.ajax({
type: "GET",
url: "Test/GetString",
data: word,
success: function (result) {
console.log("sucess: " + result);
},
error: function (result) {
console.log("failed.");
}
});
}
I forgot to do something really basic..
I had to add the Global asax file with the following code
public class Global : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
}
}
Then in my controller, I just changed the inherited class from Controller to ApiController which requires the namespace System.Web.Http
public class TestController: ApiController
{
public string GetString(string word)
{
return "Hello from Get: " + word;
}
}
Finally, in my javascript I used a different get function which worked
testFunc();
function testFunc() {
var myword = "test";
$.getJSON('api/test?&word='+myword,
function (data) {
console.log(data);
});
}