从变量后面的代码创建HTML

时间:2017-01-24 22:03:54

标签: asp.net

最近我刚学会了我可以做到这一点,我可以在我的代码后面设置readonly属性,如下所示:

readonly="<%# someOtherBoolean %>"

并像这样使用它:

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

现在在同一页面中,我有类似的东西,并再次想要使用相同的技术,但它给我语法错误,我应该做什么和有什么不同?

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

我认为我可以改为

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

2 个答案:

答案 0 :(得分:1)

如果someOtherBoolean已经是代码隐藏的变量,为什么要使用前端嵌入式表达式块?您正在从代码隐藏创建一个控件,该控件转到前端,然后在代码隐藏中搜索变量。这是一个主要的混淆。

只需使用代码隐藏中的变量:

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

答案 1 :(得分:1)

Embedded Code blocks主要用于旧ASP系统的向后兼容性。没有必要在现代系统的代码中使用它们。嵌入的代码块提供对正在服务的页面构建时在代码中声明的程序流和值的访问。

在第二个示例中,您不需要使用嵌入式代码块,因为您已经有权访问到您尝试使用的变量。你可以简单地把它写成

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