views:

826

answers:

8

How do I get to the current users name without doing it in the code-behind, just using the aspx server tags?

In code-behind I can just do this:

Label4.Text = User.Identity.Name.ToString()

But I'm trying to do it without code-behind like this:

<body>
    <form id="form1" runat="server">
    <div>
        1. <asp:Label ID="Label1" runat="server" Text="<% User.Identity.Name %>"/><br />
        2. <asp:Label ID="Label2" runat="server" Text="<%= User.Identity.Name %>"/><br />
        3. <asp:Label ID="Label3" runat="server" Text="<%# User.Identity.Name %>"/><br />
        4. <asp:Label ID="Label4" runat="server" Text="<%= Context.User.Identity.Name %>"/><br />
        5. <asp:Label ID="Label5" runat="server" Text='<%# User.Identity.Name %>' /><br />
        6. <span runat="server" ID="Span1"><%= User.Identity.Name %></span><br />
        7. <asp:LoginName ID="LoginName1" runat="server" /><br />
        8. <span><%# User.Identity.Name %></span><br />
        9. <span><%= User.Identity.Name %></span><br />
        10. <asp:Label ID="Label6" runat="server" Text='<%= User.Identity.Name %>' /><br />
    </div>
    </form>
</body>

I get the username displayed for lines 6, 7, and 9 but I really want to set a property of a control to this value and not just display it on screen.

Is it possible?

Background: I was whipping up a quick app, dragging and dropping controls on the page, and it turned out that I did it with only having 1 line in code-behind of the page(s). That line was setting the value of a hidden field to the current users name in page load so I could pass the value of that control as a param of a sqlparameter. So I thought that since I was going this route (lots of stuff in aspx that maybe shouldn't be there) I should try to be consistent with it. I don't normally do it this way, but wanted to this time

+1  A: 

Will this do the trick?

<asp:LoginName ID="LoginName1" runat="server" />
Arjan Einbu
Yes that will display the name, but I want to do it with server tags.
Keith
+1  A: 

Do you really need it in a label server control? Or could you just use the span tags rendered by the server control?

<span runat="server" ID="Label2"><%= User.Identity.Name %></span>


Update:
Okay, new goal: Get User.Identity.Name into an SqlParameter value without using the codebehind.

This is going to be tricky. The basic code tag bee-stings (<% %> and the like) don't run in the page life cycle until after your query was already executed. That means you need to handle an earlier page life cycle event yourself, and the usually means putting something in the code behind. If you really want to get rid of the code-behind you can of course include a server-side script on your page:

<%@ Page Lanuage="C#" %>
<script runat="server" language="c#">
    public void OnSelecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
       e.Command.Parameters["@UserName"].Value = User.Identity.Name;
    }
</scirpt>
<html>
<body>
    <asp:SqlDataSource runat="server" ID="MyDataSource" OnSelecting="OnSelecting" ...>
    <SelectParameters>
        <asp:Parameter Name="UserName" ... />
    </SelectParameters>
    </asp:SqlDataSource>

    <asp:GridView runat="server" ID="ResultsGrid" DataSourceID="MyDataSource" .../>

</body>
</html>

It's still writing real code, though, rather than keeping everything in markup. But I suspect it's the closest you can get here.

Joel Coehoorn
No I don't really need it in a label control, just trying to simplify my question for posting. I really want to pass the current user name as a select parameter to sqldatasource which is all specified in aspx.like this: <asp:Parameter Name="UserName" DefaultValue="mydomain\keith" />
Keith
I just thought the solution would be the same for label.text as for parameter.value.
Keith
Also, if I could get any controls value set to this username I could then specify my sqlparameter is a controlparameter and that would get me where I need to be too.
Keith
Imo, creating a custom parameter class is a cleaner and more reusable alternative to having code in codebehind or in-page like this...
Peter Lillevold
@Peter: agree, except I got the feeling he's trying to avoid a dependency on that kind of thing and wanted it all in one file.
Joel Coehoorn
@Joel - yep, trying to do it all in aspx this time, wanted to do no external files. Looks like it won't work.
Keith
You know the snippet I posted is all in the same file, right?
Joel Coehoorn
In fact, where I work we have a largish classic asp intranet. It's slowly moving to .Net, but most of it is still classic asp, with no app_code or bin folders. Anything new of consequence is .Net, but occasionally I'll use this to add an aspx page to the site.
Joel Coehoorn
@Joel, true, it's all in 1 file, which is what I asked for, but was hoping it could be done with server tags/aspx only, no C#.
Keith
+1  A: 

I'm not sure about this but,i think

<asp:Label ID="Label1" runat="server" Text='<%# User.Identity.Name %>' />

Double quotes is not a true for expressions when defined in a property. Instead of using above expression you may also print value in some html label with just writing your expression i.e.

<span><%# User.Identity.Name %></span>

And make sure that you authenticated user well enough.

Myra
<span><%= User.Identity.Name %></span> - that does generate a username but I need to set the value of something to that and not just display it, thats what I'm unable to do.
Keith
I think your concept is wrong.User.Identity.Name will not generate any username , it is getting authenticated user's name.My question is why do you wish to set it into a control's property?If your aim is to hold the username in html form so that you can use that in some script,i suggest make an ajax request and take the value from User.Identity.Name and bring it back to form.If not you can add any attribute of any html control which will be possible for server control when a request is made.i.e.label1.Attributes.Add("username",User.Identity.Name);which will print on htmlusername="..."
Myra
I really want to set a property of a control on my page to the current users name, it's simple to do in code-behind but I want to do it in aspx. I don't want to display it, just want to use it.
Keith
Then just add it into some attribute of a html elementlabel1.Attributes.Add("username",User.Identity.Name);This will not print the value,but you will store it in html.If you look at html output of page,you will observe that<label id="label1" username="Keith" />
Myra
but "label1.Attributes.Add("username",User.Identity.Name);" would be in code-behind.
Keith
A: 
<asp:Label ID="Label1" runat="server" Text='<%= User.Identity.Name %>' />

The problem is the double quotes. You will often need to use single quotes

runxc1 Bret Ferrier
Nope, that doesn't do it either.
Keith
+5  A: 

In a comment you wrote:

Also, if I could get any controls value set to this username I could then specify my sqlparameter is a controlparameter and that would get me where I need to be too.

You can create a custom parameter type.

Start by creating this class, either in App_Code or in a ASP.NET Server control dll:

namespace ParameterDemo {
    public class LoginParameter : Parameter {
        public LoginParameter(string name)
            : base(name)
        {}

        protected override object Evaluate(HttpContext context, Control control)
        {
            //UPDATED as suggested in Joels comments below...
            //return HttpContext.Current.User.Identity.Name;
            return context.Current.User.Identity.Name;
        }
    }
}

and registering it on the page (right after the @Page directive)

<%@ Register TagPrefix="put" Namespace="ParameterDemo" %>

(or optionally register it in web.config for use on all pages)

...and the you can use it like this:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    SelectCommand="SELECT * FROM MyTable WHERE SomeValue=@SomeParameter">
    <SelectParameters>
        <put:loginParameter name="SomeParameter" />
    </SelectParameters>
</asp:ObjectDataSource>

If this is what you're looking for, you should consider editing the original question...

Arjan Einbu
I really want to set a property of a control on my page to the current users name, it's simple to do in code-behind but I want to do it in aspx.
Keith
@Keith: you can do it in your aspx markup. The problem is that you can't do it until it's too late in the life cycle to matter for your SqlDataSource.
Joel Coehoorn
@Arjan: probably should use the passed httpcontext rather than context.current. Otherwise, why have the parameter at all.
Joel Coehoorn
@Joel - that makes sense, thanks Joel.
Keith
@Joel: You're right! :D I didn't see that at all...
Arjan Einbu
+3  A: 

If you really want to pass the current user name as a select parameter to SqlDataSource, I'd suggest making a quick custom parameter (either as a code file in your web project or in a separate assembly if you like):

namespace CustomParameters
{
    public class UserNameParameter : Parameter
    {
        public UserNameParameter()
        {
        }

        public UserNameParameter(string name)
            : base(name)
        { }


        protected override object Evaluate(HttpContext context, Control control)
        {
            return User.Identity.Name;
        }
    }
}

and then in your page:

<%@ Register TagPrefix="myNS" Namespace="CustomParameters" %>

...

<myNS:UserNameParameter Name="UserName" />
Peter Lillevold
Ups, @Arjan already proposed this solution... oh well :)
Peter Lillevold
I got the impression that avoiding a dependency on any external files was part of the goal. Otherwise he could just use a code-behind.
Joel Coehoorn
@Joel - yep, trying to do it all in aspx this time, wanted to do no external files. Looks like it won't work.
Keith
@Keith - why do you require all to be in one aspx? it will only give you spaghetti code... :) It would be nice if you gave some more background as to why you have this constraint.
Peter Lillevold
@Keith - Writing a 'smart' parameter class is a sensible path. Remember, you'll be adding to your toolbox! Rather than avoiding 'external files', you should look for the elegant, expressive solution. This is one.
Tor Haugen
@Peter - Background: I was whipping up a quick app, and it turned out that I did it with only having 1 line in code-behind of the page(s). That line was setting the value of a hidden field to the current users name so I could pass the value of that control as a param of a sqlparameter. So I thought that since I was going this route (lots of stuff in aspx that maybe shouldn't be there) I should try to be consistant with it. I don't normally do it this way, but wanted to this time.
Keith
@Keith - Sure. This is why I would recommend implementing the UserNameParameter, stuff it away in some other cs file or assembly, and keep your aspx free of both codebehind and inline code. Cleanest route there is :)
Peter Lillevold
A: 

One way would be to set it in the code behind:

Label1.Text = User.Identity.Name.ToString();

Another way would be to use an expression builder, such as Ricardo Peres's CodeExpressionBuilder, to bind a control property from the aspx markup:

<asp:Label runat="server" Text="<%$ Code: User.Identity.Name.ToString() %> />
orip
A: 

I suspect that you forgot to call DataBind() on your form. Label3 or Label5 should work perfectly.

Add a call to form1.Databind() in your Page_Load() and that should fix it.

Mike L