【问题标题】:Save jQuery widgets to SqlDatabase using JSON使用 JSON 将 jQuery 小部件保存到 SqlDatabase
【发布时间】:2014-11-26 15:13:14
【问题描述】:

我不久前创建了一个带有小部件的仪表板,现在我正在重新审视如何将每个用户的小部件持久保存到数据库中。我以为我在正确的轨道上,但我对 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 从未提供过。很明显我错过了如何做某事,我无法在谷歌机器上找到我错过的东西。

我用过这个link here,但这并不能解释最伟大的事情,还有一些事情让我感到困惑。

我还找到了其他链接,但没有任何内容可以解释我要完成的工作。非常感谢任何帮助!

【问题讨论】:

    标签: javascript c# asp.net json webforms


    【解决方案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; }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      相关资源
      最近更新 更多