vb.net - 如何将 Handsontable 保存到数据库

标签 vb.net json wcf jquery handsontable

是否有一种普遍接受的模式将手持表中的数据保存回数据库?

我正在使用 ajax 和 WCF 服务从数据库中提取数据来填充表。该服务返回一个对象列表,这些对象表示数据库表中的一行数据。

WCF:

<ServiceContract(Namespace:="")>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
Public Class TableService

    <OperationContract()>
    <WebGet(ResponseFormat:=WebMessageFormat.Json)>
    Public Function GetResource() As List(Of Resource)
        Dim conn = <some connection string>
        Dim sql = <some SQL>
        Dim dt = New DataTable("foo")

        Using da As New SqlDataAdapter(sql, conn)
            da.Fill(dt)
        End Using

        Return Objectify(dt)
    End Function

   Private Function Objectify(dt As DataTable) As List(Of Resource)
        Dim resourceTable = New List(Of Resource)

        For Each row As DataRow In dt.Rows
            resourceTable.Add(New Resource With {
                .ResourceAllocationID = row("ResourceAllocationID"),
                .ResourceName = row("ResourceName"),
                .AllocationPercent = row("AllocationPercent"),
                .Month = row("Month"),
                .Year = row("Year"),
                .Comments = row("Comments"),
                .ProjectID = row("ProjectID"),
                .ResourceUId = row("ResourceUId")})
        Next

        Return resourceTable
    End Function
End Class

Public Class Resource
    Public Property ResourceAllocationID As Integer
    Public Property ResourceName As String
    Public Property AllocationPercent As Integer
    Public Property Month As String
        Get
            Return _monthName
        End Get
        Set(value As String)
            Dim intMonth As Integer
            If Integer.TryParse(value, intMonth) Then
                If [Enum].IsDefined(GetType(MonthName), intMonth) Then
                    _monthName = CType(value, MonthName).ToString
                End If
            Else
                If [Enum].IsDefined(GetType(MonthName), value) Then
                    _monthName = value
                End If
            End If
        End Set
    End Property        
    Public Property Year As Integer
    Public Property Comments As String
    Public Property ProjectID As Integer
    Public Property ResourceUId As String

    Private _monthName As String

    Public Enum MonthName
        January = 1
        February = 2
        March = 3
        April = 4
        May = 5
        June = 6
        July = 7
        August = 8
        September = 9
        October = 10
        November = 11
        December = 12
    End Enum
End Class

Java脚本:

$("#container").handsontable({
    contextMenu: true,
    startRows: 1,
    minRows: 1,
    colHeaders: ['Year', 'Month', 'Name', '% Allocation', 'Comments'],
    colWidths: [52, 100, 150, 100, 200],
    columns: [
        { data: 'Year', type: 'numeric' },
        { data: 'Month' },
        { data: 'ResourceName' },
        { data: 'AllocationPercent', type: 'numeric' },
        { data: 'Comments' }
    ]
});

$.ajax({
    url: "TableService.svc/GetResource",
    type: "GET",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        $("#container").handsontable(loadData, data.d)
    },
    error: function (error) {
        alert("Error: " + error);
    }
});

这可以很好地填充表格。我正在努力解决的是如何将更改保存回数据库。要求是在所有更改完成并点击更新按钮之前不要保存任何更改。

我知道我可以通过调用handsontable.getData()来获取包含表中所有单元格的对象。我的想法是,我需要将对象序列化为 Json,将其发送回我的服务,将其反序列化回对象列表,然后更新列表中每个对象的数据库。我走在正确的轨道上吗?如果是这样,我该如何实际实现它?

最佳答案

因此,我最终拼凑了一个解决方案来满足我的特定要求。

我首先需要获取一个 JSON 格式的字符串,表示 Handsontable 的所有单元格,以传递回我的 WCF 服务。 handsontable.getData() 方法返回一个表示表中所有数据的对象。然后我使用 JSON.stringify() 将该对象转换为字符串。从那里我很难将该字符串传递给我的服务。我最终发现我必须对已经字符串化的对象进行字符串化,以便为我的服务创建正确的字符串参数,同时正确转义对象内的引号。

$("#btnUpdate").click(function () {
    var tableData = JSON.stringify(handsontable.getData());
    var input = JSON.stringify({ "input": tableData });

    $.ajax({
        type: 'POST',
        url: "TableService.svc/SaveResource",
        data: input,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (res) {
            if (res.result === 'ok') {
                console.text('Data saved');
            }
        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });
    $("btnUpdate").blur();
});

现在我的表数据返回到服务器端,我需要将 JSON 解析回对象列表。我最终使用了JSON.NET来实现这一点。获得对象列表后,我将每个列表项作为一行添加到新的 DataTable 中,我可以在其中运行更新数据库所需的 SQL。

<OperationContract()>
<WebInvoke(Method:="POST", BodyStyle:=WebMessageBodyStyle.WrappedRequest, ResponseFormat:=WebMessageFormat.Json)>
Public Function SaveResource(ByVal input As String) As String
    Dim resources As List(Of Resource) = Json.JsonConvert.DeserializeObject(Of List(Of Resource))(input)
    UpdateDB(resources)
    Return "ok"
End Function

Private Sub UpdateDB(resources As List(Of Resource))
    Dim dt As New DataTable
    Dim conn = <some connection string>
    Dim sql = <some SQL>
    Using da As New SqlDataAdapter(sql, conn)
        da.FillSchema(dt, SchemaType.Source)
        For Each resourceItem In resources
            Dim row As DataRow = dt.NewRow()
            Dim month As Resource.MonthName
            row("ResourceAllocationID") = resourceItem.ResourceAllocationID
            row("ResourceName") = resourceItem.ResourceName
            row("AllocationPercent") = resourceItem.AllocationPercent
            row("Month") = [Enum].TryParse(resourceItem.Month, month)
            row("Year") = resourceItem.Year
            row("Comments") = resourceItem.Comments
            row("ProjectID") = resourceItem.ProjectID
            row("ResourceUId") = resourceItem.ResourceUId
            dt.Rows.Add(row)
        Next
    End Using
    *<run the appropriate SQL on each row of dt to update the database>*
End Sub

关于vb.net - 如何将 Handsontable 保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16304558/

相关文章:

asp.net - 与客户端的 WCF 通知和回调

mysql - 在一个语句中计算多个

mysql - mysql select 查询的循环

vb.net - Alt 代码没有导航出用户控制

arrays - 如何使用在 Swift 4.0 中嵌套数组的数组解析 JSON?

c# - wcf 自托管多个服务

vb.net - 故意在VB.NET中导致程序崩溃

Javascript 无法正确解析 JSON 中的大量数字

java - 从 JSON 数组中提取数据

c# - Quartz.NET 只执行一次作业