【问题标题】:Web API 2 Receiving JsonWeb API 2 接收 Json
【发布时间】:2015-10-22 20:01:20
【问题描述】:
谁能给我从 jquery ajax 发送 json 数据到 web api 控制器的例子,包括客户端和服务器代码?例如,我想通过 ajax 作为发布请求发送{Name: "SomeName", Email: "SomeEmail"},并在控制器中获取这些值...
【问题讨论】:
标签:
c#
asp.net-mvc
asp.net-web-api
asp.net-web-api2
【解决方案1】:
服务器端检索值:
public class RequestModel()
{
public string Name { get; set; }
public string Email { get; set; }
}
public MyWebApiController : ApiController
{
public object Post(RequestModel model)
{
// Do something
// Return same values back
return model;
}
}
客户端发布值:
$.ajax({
type: 'POST',
dataType: 'json',
url: '/Api/MyWebApi',
data: { Name = "Bob", Email = "bob@example.com" },
success: function (responseData) {
// Do something on success, with the returned data
alert("Email:" + responseData.Email + ", Name:" + responseData.Name);
},
error: function (jqXHR, textStatus, errorThrown) {
// Display error?
}
})