【发布时间】:2013-02-20 19:08:16
【问题描述】:
刚开始使用 WebApi 并遇到多个问题。阅读大量信息,但可能缺少一些概念。
在我的控制器中:
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);
}
});
});
首先,无论我是否传递参数productName,都会调用无参数的GetProduct(并且应该返回数据)。 我需要能够调用这两种 GET 方法。 二是不调用success函数。所以我没有从 WebApi 方法中获取任何数据。
感谢任何提示或指导。谢谢。 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 }
);
}
}
现在唯一的问题是我的数据没有收到警报:
$('#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);
}
});
});
【问题讨论】:
-
dataType=''不见了,你对 webapi 有什么期待html、json、text、script? -
您检查过任何控制台错误吗?
-
没有控制台错误,数据类型相同:“json”。
-
您使用哪个版本的 jQuery?你有什么例外?
-
@Cuong Le, 1.7.1 也不例外。我添加了错误:function() { alert("error"); },到我的 $.ajax 并且它没有被提醒。
标签: jquery asp.net-mvc get asp.net-web-api