首先,我无法将模型从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>
提交表格时出现以下错误
“消息”:“未找到与请求URI匹配的HTTP资源 'http://localhost:51856/api/Contact/AddProduct'。“,” MessageDetail“:”否 在控制器“联系人”上找到与 请求。”}
答案 0 :(得分:1)
好吧,你做错了。有两种方法可以实现这一目标。
添加模型类StudentModel.cs
public class StudentModel
{
public string name { get; set; }
}
然后接受该参数作为Model-
[Route("AddProduct")]
[HttpPost]
public string Add(StudentModel model)
{
return "";
}
并在Jquery请求中->
var postData = {};
postData.name = "Tom";
$("#Result").click(function () {
$.ajax({
url: '/api/Contact/AddProduct,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: 'POST',
data: JSON.stringify(postData),
success: function (response) {
alert('hello');
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
url: '/api/Contact/AddProduct?name=' + name
中将名称作为参数传递,并在Action AddProduct中将参数作为字符串接受(不推荐,因为它是POST请求)