Just started with WebApi and have multiple problems. Read tons of info, but probably missing some concepts.
In my controller:
public IEnumerable<Product> GetProducts()
{
return db.Products.AsEnumerable();
}
public Product GetProduct(string name)
{
Product product = db.Products.FirstOrDefault(p => p.Name == name);
if (product == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return product;
}
Javascript :
$('#Search').click(function () {
jQuery.support.cors = true;
var productName = $('#Name').val();
$.ajax({
url: "http://localhost:62178/api/product",
//url: "http://localhost:62178/api/product/" + productName,
type: "GET",
success: function (data) {
alertData(data);
}
});
});
First of all, no matter if I pass a parameter productName, the parameterless GetProduct is called (and should return data back) . I need to be able to call both of these GET methods. Second, the success function is not called. so I don't get any data back from WebApi methods.
Any tips or guidance is appreciated. Thanks. WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Only problem right now is that I don't get my data alerted :
$('#Search').click(function () {
jQuery.support.cors = true;
var productName = $('#Name').val();
$.ajax({
url: "http://localhost:62177/api/product/" + productName,
//data: { name: productName },
type: "GET",
dataType: "jsonp",
error: function (request, status, error) {
alert(request.responseText);
},
success: function (data) {
alert(data);
}
});
});