【发布时间】:2019-06-11 17:02:06
【问题描述】:
首先我无法将模型从 jquery 传递到我的 web-api,所以我更改了代码并使用 GET 和 POST 编写了一个简单的控制器
using ContactInfo.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace ContactInfo.Controllers
{
[RoutePrefix("api/Contact")]
public class ContactController : ApiController
{
List<ContactDto> contactList = new List<ContactDto>
{
new ContactDto { ContactId = 1, ContactName = "x", MobileNumber="1234567890" },
new ContactDto { ContactId = 1, ContactName = "y", MobileNumber="1234567890" },
};
[HttpGet]
[Route("GetProducts")]
public IEnumerable<ContactDto> GetAllProducts()
{
return contactList;
}
[Route("AddProduct")]
[HttpPost]
public string Add(string name)
{
return name;
}
}
}
我的HTML如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<!--<button id="Result" value="Submit" />-->
<input id="Result" name="Result" type="button" value="Submit" />
<script type="text/javascript">
$(document).ready(function () {
var name = 'hi';
$("#Result").click(function () {
$.ajax({
url: 'http://localhost:51856/api/Contact/AddProduct',
contentType: "application/json; charset=utf-8",
dataType: "json",
type: 'POST',
data: name,
success: function (response) {
alert('hello');
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
我在提交表单时遇到的错误如下
"Message":"未找到与请求 URI 匹配的 HTTP 资源 'http://localhost:51856/api/Contact/AddProduct'.","MessageDetail":"否 在与 请求。”}
【问题讨论】:
标签: c# jquery .net asp.net-web-api