Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use User.Identity.Name as a parameter for SqlDataSource in ASP.NET?

For SqlDataSource I can configure the external source for the incoming paramater. For example it might be a QueryString, Session, Profile and so on. However I do not have an option to use User as a source.

I know that I could provide value for the parameter in Inserting,Selecting,Updating,Deleting events. But I do not think that this is an ellegant solution because I have some parameteres already definied in aspx file. I do not want to have parameters defined in two separate places. It makes mess.

So can I somehow define this parameter in .aspx file?

    <SelectParameters>
        <asp:QueryStringParameter DefaultValue="-1" Name="ID" 
            QueryStringField="ID" />
        //User.Identity.Name goes here as a value for another parameter  
    </SelectParameters> 
like image 672
Wodzu Avatar asked Oct 05 '10 12:10

Wodzu


2 Answers

You can also accomplish this by creating a hidden textbox on the page, apply the User.Identity.Name to the value and then use the formcontrol parameter in the SQL data source. The advantage here is that you can reuse the code in the select, insert, delete, and update parameters without extra code.

So in aspx we have (noneDisplay is a css class to hide it):

<asp:TextBox runat="server" ID="txtWebAuthUser" CssClass="noneDisplay"></asp:TextBox>

and in the Update parameter of the sql datasource update section:

<asp:ControlParameter Name="CUrrentUser"  ControlID="txtWebAuthUser" Type="String" PropertyName="Text" />

which gets interpreted in the update something like this:

UpdateCommand="UPDATE [Checks] SET [ScholarshipName] = @ScholarshipName, [Amount] = @Amount,LastModifiedBy=@CUrrentUser,
         [LastModified] = getdate() WHERE [CheckId] = @CheckId"

and then in the .cs file form load we have:

this.txtWebAuthUser.Text = User.Identity.Name; 

This technique has worked well in many places in all of our applications.

like image 82
done_merson Avatar answered Sep 18 '22 23:09

done_merson


Declare it in your .aspx and fill it in your codebehind:

aspx

<asp:Parameter Name="username" Type="String" DefaultValue="Anonymous" />

codebehind

protected void Page_Init(object sender, EventArgs e) {
    DataSource.SelectParameters["username"].DefaultValue = User.Identity.Name;
}
like image 25
Jan Jongboom Avatar answered Sep 18 '22 23:09

Jan Jongboom