使用 JSON 将 jQuery 小部件保存到 SqlDatabase

本文关键字:保存 SqlDatabase 小部 JSON jQuery 使用 | 更新日期: 2023-09-27 18:32:11

我不久前创建了一个带有小部件的仪表板,现在我正在重新审视如何将每个用户的小部件保存到数据库中。我以为我走在正确的轨道上,但我对 JSON 很陌生,我无法完成我需要的东西。我已经对此进行了研究并尝试了多种方法,但到目前为止没有任何效果。这是我的代码。

创建要更新的项目的JavaScript

function updateWidgetData() {
    var items = [];
    $('.column').each(function () {
        var columnId = $(this).attr('id');
        $('.dragbox', this).each(function (i) {
            var collapsed = 0;
            if ($(this).find('.dragbox-content').css('display') == "none")
                collapsed = 1;
             //Create Item object for current panel  
            var item = {
                id: $(this).attr('id'),
                collapsed: collapsed,
                order: i,
                column: columnId
             };
             //Push item object into items array  
             items.push(item);
         });
     });

//Assign items array to sortorder JSON variable  
var sortorder = { items: items };

现在我的目标是将要保存到数据库的排序顺序传递给数据库......但我有这个进行测试..

var testData = '{ "Column1": "test1", "Column2": "test2"}'
$.ajax ({
    url: "/Handlers/SaveWidgets.ashx",
    type: "POST",
    contentType: "application/json; charset=uft-8",
    dataType: "json",
    data: testData,
    success: function (response) {
        alert("Passed json");
    },
    error: function (error) {
        alert("Failed passing json.");
    }
 });

然后在我的处理程序中..

public void ProcessRequest(HttpContext context)
{
   context.Response.ContentType = "application/json";
   string column1 = (string)context.Request.Form["Column1"];
   string column2 = (string)context.Request.Form["Column2"];
   using (SqlConnection connCao = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString))
    {
       using(SqlCommand cmdWidget = new SqlCommand("INSERT INTO TestTable (Column1, Column2) VALUES (@column1, @column2)", connCao))
       {
            cmdWidget.Parameters.AddWithValue("@column1", column1);
            cmdWidget.Parameters.AddWithValue("@column2", column2);
            connCao.Open();
            cmdWidget.ExecuteNonQuery();
            connCao.Close();
        }
     }
 }

但我明白它期待@column1参数,以及从未提供过的@column2参数。很明显,我错过了如何做某事,我无法在谷歌机器上找到我缺少的东西。

我在这里使用了这个链接,但这并不能解释最大的,有些事情让我感到困惑。

我还找到了其他链接,但没有任何东西可以解释我想要完成的目标。任何帮助将不胜感激!

使用 JSON 将 jQuery 小部件保存到 SqlDatabase

我将首先创建一个类来表示您发布到处理程序的数据。

using System;
using System.Runtime.Serialization;
[DataContract]
public class YourDataModel
{
    public YourDataModel() { }
    // When a property in your model doesn't 
    // match up exactly you can manually 
    // specify the name
    [DataMember(Name = "Column1")]
    public String Col1 { get; set; }
    // If things match up exactly (including case)
    // you don't need to manually map the Name
    [DataMember]
    public String Column2 { get; set; }
}

然后修改处理程序,从发布的 JSON 数据创建该类的实例。

using System;
using System.IO;
using System.Web;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public class SaveWidgets : IHttpHandler {
    public void ProcessRequest (HttpContext context) 
    {
        String json = String.Empty;
        // you have sent JSON to the server
        // read it into a string via the input stream
        using (StreamReader rd = new StreamReader(context.Request.InputStream))
        {
            json = rd.ReadToEnd();
        }
        // create an instance of YourDataModel from the
        // json sent to this handler
        YourDataModel data = null;
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(YourDataModel));
        using (MemoryStream ms = new MemoryStream())
        {
            byte[] utf8Bytes = Encoding.UTF8.GetBytes(json);
            ms.Write(utf8Bytes, 0, utf8Bytes.Length);
            ms.Position = 0;
            data = serializer.ReadObject(ms) as YourDataModel;
        }
        // update the DB and
        // send back a JSON response
        int rowsUpdated = 0;
        using (SqlConnection c = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString))
        {
            c.Open();
            String sql = @"
                INSERT INTO TestTable 
                    (Column1, Column2) 
                  VALUES 
                    (@column1, @column2);";
            using (SqlCommand cmd = new SqlCommand(sql, c))
            {
                cmd.Parameters.Add("@column1", SqlDbType.VarChar, 50).Value = data.Col1;
                cmd.Parameters.Add("@column2", SqlDbType.VarChar, 50).Value = data.Column2;
                rowsUpdated = cmd.ExecuteNonQuery();
            }
        }
        context.Response.ContentType = "application/json";
        context.Response.Write("{ '"rows_updated'": " + rowsUpdated + " }");
    }
    public bool IsReusable {
        get { return false; }
    }
}