简体   繁体   中英

Insert Json Object into SQL Server 2008 using Ajax Webmethod

function AddJSon() {
    var jsonArr = [];
    for (var i = 1; i < 4; i++) {
        for (var j = 0; j < 3; j++) {
            var ProductId = $("#hfProductId" + i + "_" + j).val();
            if (ProductId != undefined) {
                jsonArr.push({
                    SalesOrderItemId: $("#hfProductId" + i + "_" + j).val(),
                    AttachmentCode: $("#txtAttachmentCode" + i + "_" + j).val(),
                    AttachmentName: $("#txtAttachName" + i + "_" + j).val(),
                    Qty: $("#txtAttachmentQty" + i + "_" + j).val(),
                    UnitCost: $("#txtAttachCost" + i + "_" + j).val(),
                    TotalCost: $("#txtAttachmentTotalCost" + i + "_" + j).val(),
                })
            }
        }
    }
}

In Above code i have pushed the values of various fields in Json array and now i want to save them in database without using loop.

I will step down the thing you want to do next.

  1. Since you have already got your JSON you can create a web method in required page's asxp.cs.(I named it AddJSon())

  2. This method should accept a parameter type of the JSON format what we already have.So create a class for that.(I named it JsonDataList) Your request objects should be as follows.

     public class JsonDataList { public List<JsonData> jsonData { get; set; } } public class JsonData { public int SalesOrderItemId { get; set; } public string AttachmentCode { get; set; } public string AttachmentName { get; set; } public int Qty { get; set; } public decimal UnitCost { get; set; } public decimal TotalCost { get; set; } } 
  3. Then you have to create your table for this.I assume you are using MSSQL and you would be able to create your table structure accordingly.(connection strings etc. too)

  4. When part 3 is done, Your web method should be changed like following to insert data to created table.(i will do it in the web method itself which is not good)

     [WebMethod] public static string AddJSon(JsonDataList jsonDataList) { try { using(SqlConnection con=new SqlConnection("your_connection_String")) { con.Open(); foreach(JsonData data in jsonDataList) { string query = "INSERT into table (column1,column2,column3,...) VALUES (@value1,@value2,@value3,..)"; SqlCommand command = new SqlCommand(query, con); command.Parameters.Add("@value1",data.SalesOrderItemId); command.Parameters.Add("@value2",data.AttachmentCode ); command.Parameters.Add("@value3",data.AttachmentName ); . . command.ExecuteNonQuery(); } } return "Success"; }catch(Exception e) { return "Error"; } } 

hope this might be helpful for you.This doesn't have any validations or any good practices.Just get the idea from this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM