【问题标题】: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?
    }
})

【讨论】:

    猜你喜欢
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2014-05-22
    • 1970-01-01
    相关资源
    最近更新 更多