Session Variable - The name does not exist in current context

1.5k Views Asked by At

I keep getting the error "The name "User Name" does not exist in the current context. As you can see "UserName" is clearly defined on my code behind page and I am referencing my page. So why does it say that it does not exist?

Here is my C# -

public partial class Account_Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {}

    protected void btnLogOn_Click(object sender, EventArgs e)
    {
        Session["SubName"] = UserName.Text;
    }
}

Here is my HTML -

<p>
        Please enter your username and password.
    </p>

    <form action="/Account/LogOn" method="post">
        <div>
            <fieldset>
                <legend>Account Information</legend>

                <div class="editor-label">
                    <label for="UserName">User name</label>
                </div>
                <div class="editor-field">
                    <input id="UserName" name="UserName" type="text" value="" />

                </div>

                <div class="editor-label">
                    <label for="Password">Password</label>
                </div>
                <div class="editor-field">
                    <input id="Password" name="Password" type="password" />

                </div>

                <p>
                    <input id="btnLogOn" type="submit" value="Log On" />
                </p>
            </fieldset>
        </div>
    </form>
        </div> 
5

There are 5 best solutions below

0
On

Your input box needs to have runat=server if you want to access it from code behind.

<input id="UserName" name="UserName" type="text" value="" runat=server />

Otherwise you will receive an error that UserName does not exist, as you have already mentioned.

0
On

"UserName" is clearly defined on my code behind

No, it's not - you have a client side control called UserName but nothing in the code-behind. You can either make it a server control by adding 'runat="server"' to the form and control, or reference the form variable in the code-behind:

protected void btnLogOn_Click(object sender, EventArgs e)
{
    Session["SubName"] = Request["UserName"]; // pull value from form variable
}
2
On

Add runat="server" to the label control?

0
On

You should have 'runat="server"' in UserName

<input id="UserName" name="UserName" type="text" value="" runat="server" />
0
On

UserName object corresponding to the control needs to be present in the designer.cs file of the page you are working on. This will be auto generated on page save, but only if you create your control as a server side control. So marking the input control with runat="server" should do the trick.