Bohn
Bohn

Reputation: 26919

Creating the HTML from a code behind variable

Recently I just learned I can do this, where I can set the readonly attribute from my code behind value like this:

readonly="<%# someOtherBoolean %>"

and used it like this:

<textarea 
         name="txtSomeThing" 
         tabindex="1" 
         id="txtSomeThing" 
         style="overflow: auto;" 
         rows="12" 
         cols="80"
         readonly="<%# someOtherBoolean %>">
</textarea>

Now in the same page I have something like this and again want to use the same technique but it gives me syntax errors, what should I do and what is different?

HttpContext.Current.Response.Write("<textarea  style=""overflow:auto"" cols=60 rows=2 ")

Which I thought I can change to

HttpContext.Current.Response.Write("<textarea readonly="<%# someOtherBoolean %>" style=""overflow:auto"" cols=80 rows=4 ")

Upvotes: 0

Views: 64

Answers (2)

CDspace
CDspace

Reputation: 2689

Embedded Code blocks are mainly provided for backwards compatability for older ASP systems. There is no need to use them in the code behind in modern systems. The embedded code blocks provide access to program flow and values declared in the code behind while the page being served is built.

In your second example, you don't need to use the embedded code block because you already have access to the variable you are trying to use. You can simply write it as

HttpContext.Current.Response.Write( "<textarea readonly=\"" + someOtherBoolean.ToString() + "\" style=\"overflow:auto\" cols=80 rows=4 " )

Upvotes: 1

Tyler Roper
Tyler Roper

Reputation: 21672

If someOtherBoolean is already a variable on the code-behind, why use an front-end embedded expression block? You're creating a control from the code-behind, that goes to the front-end, that then searches for a variable on the code-behind. It's a major obfuscation.

Just use the variable from the code-behind:

HttpContext.Current.Response.Write("<textarea readonly='" & someOtherBoolean.ToString() & "' style=""overflow:auto"" cols=80 rows=4 ")

Upvotes: 1

Related Questions