Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String variable out of context for use in HTML output

Tags:

c#

asp.net

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>
like image 322
matthewpavkov Avatar asked Jan 23 '26 03:01

matthewpavkov


2 Answers

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.

like image 114
Duncan Howe Avatar answered Jan 24 '26 20:01

Duncan Howe


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.

like image 26
Muhammad Akhtar Avatar answered Jan 24 '26 19:01

Muhammad Akhtar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!