在asp.net中使用Web API插入数据

时间:2014-12-08 09:16:41

标签: c# json asp.net-mvc-4 asp.net-web-api

我是asp.net&的初学者我陷入了使用Web API插入数据而不使用Entity Framework的问题。我需要使用API​​将数据从移动应用程序存储到我的数据库中。数据将采用JSON格式,来自移动设备&需要在数据库中插入。 HttpPost用于此吗?如果是,那么它将如何完成? 请帮帮我...

修改 我使用此代码从数据库中获取数据......

HTTPGET

public HttpResponseMessage aisleshelf(string ApiKey, string storeId = "")
{
    headerParameter objheaderParameter = new headerParameter();
    string Url = Convert.ToString(Request.RequestUri);
    Url = Url.Replace("'", "''");
    DBClass objDbclass = new DBClass();
    DataSet ds = new DataSet();
    string CustomerId = null, Description = null, Aisle = null;
    Boolean UStatus = true;
    Boolean ErrorStatus = false;
    List<Aisle> objlistAisle = new List<Aisle>();
    List<AisleShelf> objlistAisleShelf = new List<Models.AisleShelf>();
    List<Aislelist> objlistAislelist = new List<Aislelist>();
    Aislelist objAislelist = new Aislelist();
    aisleshelfitem objaisleshelfitem = new aisleshelfitem();
    int Code;
    HttpResponseMessage response;
    UserValid(ApiKey, Url, out UStatus, out  CustomerId, out Code, out Description, UserIpAddress);
    if (UStatus)
    {
        ds = objDbclass.AisleShelf(ApiKey, Url, out ErrorStatus, UserIpAddress, storeId);
        // This will forward to my class where i wrtir a method to get data using stored procedure.
    }

我需要创建一个apicontroller来插入数据。

请参阅此文章,其中数据通过webmethod插入数据库。 http://www.webcodeexpert.com/2014/11/jquery-ajax-json-example-in-aspnet-to.html

现在在我的情况下,用户通过手机发送数据来调用我的api将他的记录插入数据库。

1 个答案:

答案 0 :(得分:0)

在控制器中使用类似这样的东西

dynamic json = JValue.Parse(this.HttpContext.Request.Params[0]);
JToken jt = json.postRequest;

在视图中,即网页我使用jQuery ajax

$.ajax({
       type:'POST',
       url: '/Template/DataGridList',
       dataType: 'json',
       data: JSON.stringify({postRequest:postRequest}),
       success: function (data) {
          $dfd.resolve(data);
       },
       error: function () {
          $dfd.reject();
       }
 });