Skip to content Skip to sidebar Skip to footer

Save Jquery Widgets To Sqldatabase Using Json

I created a dashboard with widgets awhile ago and I'm now revisiting how to persist the the widgets per user to the database. I thought I was on the right track, but I'm very new t

Solution 1:

I would start by creating a class to represent the data you are posting to the handler.

using System;
using System.Runtime.Serialization;

[DataContract]
publicclassYourDataModel
{
    publicYourDataModel() { }

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

Then modify your handler to create an instance of that class from posted JSON data.

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;

publicclassSaveWidgets : IHttpHandler {

    publicvoidProcessRequest (HttpContext context) 
    {
        String json = String.Empty;
        // you have sent JSON to the server// read it into a string via the input streamusing (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 responseint 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 + " }");
    }

    publicbool IsReusable {
        get { returnfalse; }
    }
}

Post a Comment for "Save Jquery Widgets To Sqldatabase Using Json"