gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:20:15 29 4
gpt4 key购买 nike

我不久前创建了一个带有小部件的仪表板,现在我正在重新考虑如何将每个用户的小部件保存到数据库中。我认为我走在正确的轨道上,但我对 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但这并不能解释最重要的事情,还有一些事情让我感到困惑。

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

最佳答案

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

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

关于javascript - 使用 JSON 将 jQuery 小部件保存到 SqlDatabase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27152599/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com