有人能举例说明将json数据从jquery ajax发送到web api控制器,包括客户端和服务器代码吗?例如,我想通过ajax发送{Name: "SomeName", Email: "SomeEmail"}
作为post请求,并在控制器中获取这些值...
答案 0 :(得分: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?
}
})