在我的 ASP.NET 应用程序中,我有以下有效的 SQL:
<asp:SqlDataSource ID="ISESDatabase" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [id], [Word], [Definition], [Example] FROM [gridData] WHERE [Strategy]='Vocabulary'">
但是,我需要在Where子句中添加用户ID检查,并希望使用user.identity.Name来执行检查。我已尝试以下方法,但不起作用:
<asp:SqlDataSource ID="ISESDatabase" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [id], [Word], [Definition], [Example] FROM [gridData] WHERE [userid]= /'" + user.identity.Name + "/' AND [Strategy]='Vocabulary'">
这是错误:
解析器错误 描述:解析服务此请求所需的资源时发生错误。请查看以下特定解析错误详细信息并适当修改您的源文件。
解析器错误消息:服务器标记格式不正确。
来源错误:
Line 46: <asp:SqlDataSource ID="ISESDatabase" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [id], [Word], [Definition], [Example] FROM [gridData] WHERE [userid]=/'" + User.Identity.Name + "/' AND [Strategy]='Vocabulary'">
我做错了什么?
最佳答案
我认为你需要重新考虑你的方法。不要尝试对 asp:SqlDataSource 元素中的“user.Identity.Name”属性进行“硬编码”,而是尝试创建一个参数来保存此值:
1) 将 SelectCommand 中的“user.Identity.Name”替换为参数标记,例如“@Name”。
2) 然后为 asp:SqlDataSource 定义一个 Name 属性为“Name”的 SelectParameter 元素。将参数的 Type 属性设置为“user.Identity.Name”的数据类型。
3) 然后,您可以在 SqlDataSource 的 Selecting 事件的事件处理程序中以编程方式定义要选择的值。
这是一个有效的示例。以下代码片段来自 aspx 页面:
<asp:GridView ID="myGridView" runat="server" DataSourceID="myDataSource" DataKeyNames="ID"></asp:GridView>
<asp:SqlDataSource ID="myDataSource" runat="server"
SelectCommand="SELECT * FROM [Users] WHERE [Name] = @Name"
ConnectionString='Data Source=(LocalDB)\v11.0;AttachDbFilename="c:\users\windowsLogin\documents\visual studio 2012\Projects\WebApplication1\WebApplication1\App_Data\Database1.mdf";Integrated Security=True'>
<SelectParameters>
<asp:Parameter Name="Name" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
然后,在隐藏代码中,您可以根据任何重要的标准在运行时以编程方式定义参数。 (在这里,我只是将值“2”分配给@Name参数;您可以将其替换为“user.Identity.Name”。)
Private Sub myDataSource_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles myDataSource.Selecting
e.Command.Parameters("@Name").Value = 2
End Sub
我希望这是清楚的...如果没有,请参阅 MSDN 上的文档。以下是帮助您入门的几页:
SqlDataSource.SelectCommand Property
SqlDataSourceSelectingEventArgs Class
更一般地说,
关于sql - 在 SQL 语句中使用 user.identity.Name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32791329/