I have just come back to this requirement again as I was pulled away from it to do more important requirements at the time.
I have asked a similar question here and the answer has helped. However, in that question, I was passing test data and saving it to the database. I'm unable to figure out how to save the actual widget information however. The link helped me with passing the json successfully.
I receive this message when trying to save the data.
jQuery
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 };
$.ajax({
url: "/Handlers/SaveWidgets.ashx",
type: "POST",
contentType: "application/json; charset=uft-8",
dataType: "json",
data: JSON.stringify(sortorder),
success: function (response) {
alert("Passed json");
},
error: function (error) {
alert("Failed passing json.");
}
});
Handler
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
SaveWidgetsDAL data = null;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SaveWidgetsDAL));
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 SaveWidgetsDAL;
}
// update the DB and
// send back a JSON response
int rowsUpdated = 0;
foreach (var item in data.wdata)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE tWidgetControl SET SortNo = @SortNo, ColumnId = @ColumnId, Collapsed = @Collapsed "
+ "WHERE UserId = @UserId AND WidgetId = @WidgetId;", conn))
{
cmd.Parameters.AddWithValue("@SortNo", item.SortNo);
cmd.Parameters.AddWithValue("@ColumnId", item.ColumnId);
cmd.Parameters.AddWithValue("@Collapsed", item.Collapsed);
cmd.Parameters.AddWithValue("@UserId", "2");
cmd.Parameters.AddWithValue("@WidgetId", item.WidgetId);
rowsUpdated = cmd.ExecuteNonQuery();
}
conn.Close();
}
}
context.Response.ContentType = "application/json";
context.Response.Write("{ \"rows_updated\": " + rowsUpdated + " }");
}
public bool IsReusable
{
get
{
return false;
}
}
Widgets Data Class
public class SaveWidgetsDAL
{
public List<Widgets> wdata { get; set; }
public SaveWidgetsDAL() { }
public class Widgets
{
[DataMember]
public string SortNo { get; set; }
[DataMember]
public string ColumnId { get; set; }
[DataMember]
public string Collapsed { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string UserId { get; set; }
[DataMember]
public string WidgetId { get; set; }
}
}
I would imagine that I would need to save the json into a list and then insert/update each widget information into the database. However, I receive the error above when I try this. I'm clearly missing something, but I am not sure what it is. This error occurs in my handler, but the list in the SaveWidgetsDAL is empty, causing the NullReference. I am not sure what I am missing or sure where to go from here. Any help is greatly appreciated!
EDIT 1:
I have changed my database around a bit along with my SaveWidgetsDAL.
SaveWidgetsDAL
[DataContract]
public class SaveWidgetsDAL
{
[DataMember(Name = "items")]
public List<Widgets> wdata { get; set; }
public SaveWidgetsDAL() { }
public class Widgets
{
[DataMember(Name = "order")]
public string SortNo { get; set; }
[DataMember(Name = "column")]
public string ColumnId { get; set; }
[DataMember(Name = "collapsed")]
public string Collapsed { get; set; }
[DataMember(Name = "id")]
public string Title { get; set; }
}
}
Handler (just the foreach)
foreach (var item in data.wdata)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE tWidgetTest SET Title = @Title, SortNo = @SortNo, ColumnId = @ColumnId, Collapsed = @Collapsed "
+ "WHERE UserId = @UserId AND Title = @Title;", conn))
{
cmd.Parameters.AddWithValue("@Title", item.Title);
cmd.Parameters.AddWithValue("@SortNo", item.SortNo);
cmd.Parameters.AddWithValue("@ColumnId", item.ColumnId);
cmd.Parameters.AddWithValue("@Collapsed", item.Collapsed);
cmd.Parameters.AddWithValue("@UserId", "2");
rowsUpdated = cmd.ExecuteNonQuery();
}
conn.Close();
}
}
However, I now get this error when inserting into the database.
I'm able to see that my foreach count is 11, but the Collapsed, SortNo, ColumnId, Title are all null for each item.