3

I'm trying to understand why the variable myUrl is out of context in the example below. What's the best way to handle this situation? Are there alternatives? The code is C# in an ASP.NET page.

<% string myUrl = "http://www.website.com"; %>
<ul class="footerLinks">
    <li><a href="<%= myUrl %>/index.html">Home</a></li>
</ul>
1
  • "Out of context" means "out of scope"? What happens in your case? Your code snippet works for me. The "Home" list item does have href pointing to "website.com/index.html". I tested it on VWD Express 2010. Commented May 31, 2011 at 16:44

2 Answers 2

2

It's because the <%= is being rendered before the script component. If you set myUrl in the code behind (Page_Load or Init event) then it should come through into the page as you are expecting. Obviously, remove the variable declaration in the markup as well.

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

2 Comments

While that is a solution, it doesn't explain why the string declaration is out of scope when it is called upon in the <li> tag.
It's because the myUrl variable hasn't been defined when the renderer interprets the <%= markup. If the variable was defined but not initialised in the code behind, then I guess a NullReferenceException would ensue.
2

First of all your string variable should be set to public at the Class level.

public String myUrl

Then you need to call the DataBind() method in the Page_PreRenderComplete event:

protected void Page_PreRenderComplete(object sender, EventArgs e)
{
    DataBind();
}

Because <%= expressions are evaluated at render time.

Comments

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.