使用JSON将jQuery小部件保存到Sql数据库

时间:2014-11-26 15:13:15

标签: javascript c# asp.net json webforms

我之前创建了一个带有小部件的仪表板,我现在正在重新审视如何将每个用户的小部件持久保存到数据库中。我以为自己走在正确的轨道上,但我对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 };

现在我的目标是将sortorder传递给数据库...但是我有这个用于测试..

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。很明显,我错过了如何做某事,而且我无法找到我在谷歌机器上遗漏的东西。

我已经使用了这个link here,但这并不能解释最让我困惑的一些事情。

我还找到了其他链接,但没有解释我想要完成的事情。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

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

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; }
    }
}