0

How can i assign variable in aspx page?

See i have tried

 <div>
      <asp:TextBox ID="UsernameTextBox" Text="xxx" runat="server"></asp:TextBox>
      <%= string ss=  UsernameTextBox.Text.ToString() %>
      <asp:Button ID="btnLogin" runat="server" 
           OnClientClick="LoginPopup( <%=  UsernameTextBox.Text  %>);  return false;"
           CssClass="login-button" Text="xxx">
      </asp:Button>
 </div>

I have assigned usernametextbox value in string

 <%= string ss =  UsernameTextBox.Text.ToString() %>

But it's showing error like : Invalid Expression term 'string'

Why i can't do that? Is it possible?

But if i remove the "string ss= " then it's <%= UsernameTextBox.Text.ToString() %> working good.

I can't assign the values to a string variable. Why?

Is a bug in .net?or any wrong syntax format?

1

2 Answers 2

7

If you have to assign a value to variable then you should use normal script tag like:

<% string ss = UsernameTextBox.Text.ToString(); %>

Later if you want to render that value then you can do:

<%= ss %>

You may see: Embedded Code and Inline Server Tags

Sign up to request clarification or add additional context in comments.

2 Comments

Gooood. Now i get the value <asp:Button ID="btnLogin" runat="server" OnClientClick="LoginPopup( '<% ss %>'); return false;" CssClass="login-button" Text="xxx"></asp:Button> .but it's not working
@RameshRajendran, it should be <%=, not just <%
0

In addition to be rather non-so-elegant Spaghetti code, your logic is also flawed and you will always get the initial textbox value, not the current value at the time of clicking.

To kill two birds in one shot and have both better code style and working code, first change the markup to be just this:

<asp:Button ID="btnLogin" runat="server" OnClientClick="return LoginPopup();" CssClass="login-button" Text="xxx"></asp:Button>

Now have this in your JS function:

function LoginPopup() {
    var name = document.getElementById("<%=UsernameTextBox.ClientID%>").value;
    //...code using the name here...
    return false;
}

You read the value at the time of clicking now.

1 Comment

So don't use it. I just show more elegant way for the sake of those who will want to use it. Also, see what happens if the user name contains a single quote. (hint: your code will break, this code will not)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.