简体   繁体   English

VB.net-在SQL更新命令中传递自定义参数

[英]VB.net - Pass Custom Parameter in SQL Update Command

I am using a Gridview with SQLDataSource Select/Insert/Update command. 我正在使用带有SQLDataSource选择/插入/更新命令的Gridview。 It works fine for updating or changing value using the Gridview. 它适合使用Gridview更新或更改值。 However recently I added another plugin which use Javascript to retrieve data and I need that retrieve data to be the source data of the SQL. 但是最近我添加了另一个使用Javascript检索数据的插件,我需要将该检索数据作为SQL的源数据。 Any way I can do this? 有什么办法可以做到吗?

Something like this: 像这样:

<form id="form1" runat="server">
    <div>
    <input type="hidden" id="newname" runat="server" />
    <br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID_AM" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:BoundField DataField="StaffID" HeaderText="StaffID" SortExpression="StaffID" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
         SelectCommand="SELECT [ID], [Name], [StaffID] FROM [Record]"        
         ConflictDetection="CompareAllValues" 
         UpdateCommand="UPDATE [Record] SET [Name] = @Name, [StaffID] = @StaffID WHERE [ID] = @original_ID AND (([Name] = @original_Name) OR ([Name] IS NULL AND @original_Name IS NULL)) AND (([StaffID] = @original_StaffID) OR ([StaffID] IS NULL AND @original_StaffID IS NULL))">
        <UpdateParameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="StaffID" Type="String" />
            <asp:Parameter Name="original_ID" Type="Int32" />
            <asp:Parameter Name="original_Name" Type="String" />
            <asp:Parameter Name="original_StaffID" Type="String" />
        </UpdateParameters>
    </asp:SqlDataSource>
</div>
</form>

When I use the Gridview to update row, the plugin will generate a new name and store in the hidden input "newname.value". 当我使用Gridview更新行时,插件将生成一个新名称并将其存储在隐藏的输入“ newname.value”中。 How can I put this value into the update parameter? 如何将此值放入update参数?

I am thinking a few ways to do: 我正在考虑几种方法:

  • Find some way so that the SQL Parameter will somehow take that value 找到某种方法,以便SQL参数以某种方式采用该值
  • Override the update command using the normal SQL update. 使用常规SQL更新覆盖update命令。 But I want to keep the optimistic concurrency feature. 但我想保留乐观并发功能。

You are using asp.net webforms I assume, that being said there is no (easy) way to make the server side asp.net datasource interface with the client side javascript, without writing your own asp.net control based off of the javascript plugin. 我假设您使用的是asp.net网络表单,也就是说,没有(简单)的方法可以使服务器端的asp.net数据源与客户端javascript保持接口,而无需基于javascript插件编写自己的asp.net控件。

That being said, the easiest way that I found was using webmethods. 话虽这么说,我发现最简单的方法是使用web方法。 If you prefer using Jquery see this link . 如果您更喜欢使用Jquery,请参阅此链接 If you want asp.net to do the heavy lifting see this link . 如果您希望asp.net做繁重的工作,请参阅此链接 I prefer link 2, so here is the jist: 我更喜欢链接2,所以这里是jist:

First, you will need to add a scriptManager to your page, which will "write" javascript functions to make asynchronous calls to the server-side webmethods, this will be in your aspx file: 首先,您需要在页面上添加一个scriptManager,它将“编写” javascript函数以异步调用服务器端网络方法,这将在您的aspx文件中:

<head runat="server">
    <title></title>
    <script type="text/javascript">
        function HandleIT() {
            var name = document.getElementById('<%=txtname.ClientID %>').value;
            var address = document.getElementById('<%=txtaddress.ClientID %>').value;
            PageMethods.ProcessIT(name, address, onSucess, onError); 
            function onSucess(result) {
                alert(result);
            }
            function onError(result) {
                alert('Something wrong.');
            }
        }
    </script>
</head>
<div>
        <p>Say bye-bey to Postbacks.</p>

        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
        <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
    </div>

And here is the webmethod, (this will be in your .aspx.vb file): 这是网络方法,(将在您的.aspx.vb文件中):

Imports System.Web.Services
<WebMethod> _
Public Shared Function ProcessIT(name As String, address As String) As String
    Dim result As String = (Convert.ToString((Convert.ToString("Welcome Mr. ") & name) + ". Your address is '") & address) + "'."
    Return result
End Function

You could make a webmethod for each sql query but even then I don't think you can reference those SqlDataSource objects. 您可以为每个sql查询创建一个web方法,但是即使那样,我也不认为您可以引用那些SqlDataSource对象。 You will need to use a different way to pull data with vb.net and then return that data from the webmethod. 您将需要使用另一种方式通过vb.net提取数据,然后从web方法返回该数据。

Webmethods use JSON to send and receive objects, meaning they serialize and deserialize objects to and from JSON for you. Web方法使用JSON来发送和接收对象,这意味着它们会为您从JSON序列化对象和反序列化对象。 The object type I found that was most compatible to return to javascript was list(of dictionary(of string, object))) so your JSON would look like this: 我发现返回到javascript最兼容的对象类型是list(of dictionary(of string(object,)))),因此您的JSON如下所示:

[{"ID": 6, "Name":"sec0ndHand","StaffId" : "employeeOfTheMonth1"},{"ID": 3, "Name":"Tomy","StaffId" : "notEmployeeOfTheMonth1"}]

so your webmethod would look something like this in the end: 因此您的网络方法最终看起来像这样:

<WebMethod> _
Public Shared Function ProcessIT(name As String, address As String) As list(of dictionary(of string, object)))
    Dim result As list(of dictionary(of string, object))) = New list(of dictionary(of string, object)))
    'get/update/delete/insert your data

    'convert your return object into list(of dictionary(of string, object)))
    Return result
End Function

Thanks for your answer. 感谢您的回答。 Later I find a more straight forward method, seems easier and seems work for my case. 后来,我找到了一种更简单的方法,似乎更简单,并且可以解决我的问题。

I just add the parameters on the updating event: 我只是在更新事件上添加参数:

Protected Sub SQL_Update(source As Object, e As SqlDataSourceCommandEventArgs) Handles SqlDataSource.Updating

    dim staffid as string = newname.valie
    // presudo for other passing values

    e.Command.Parameters("@StaffID").Value = staffid
    //and for other parameters

End Sub

It can then adding those custom parameter before executing the SQL update 然后可以在执行SQL更新之前添加这些自定义参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM