<%if (CanRemove) Response.Write("<b>"+ProductName+"</b>"); %>
这段代码让我感到不舒服。具体来说,每当我在ascx或aspx文件中看到调用Response.Write的时候,我就会怀疑我做错了什么。也许这是因为之前使用XSLT时注意到,如果正确使用,很少需要
<xsl:text>
元素来生成html。我觉得当我的html代码隐藏在<% %>
块中时,它干扰了我阅读代码的能力。这只是我需要习惯Asp.Net还是有更好的方法?
<%if (CanRemove) Response.Write("<b>"+ProductName+"</b>"); %>
<xsl:text>
元素来生成html。我觉得当我的html代码隐藏在<% %>
块中时,它干扰了我阅读代码的能力。<% if (CanRemove) { %><b><%= ProductName %></b><% } %>
<%=
等同于 Response.Write。
并且作为格式良好的代码:
<% if (CanRemove) { %>
<b><%= ProductName %></b>
<% } %>
<asp:Literal>
控件,并将其 Visible
属性绑定(或手动设置)到 CanRemove
,其内容为特定文本。<asp:Literal>
解决方案更加一致。<% if (CanRemove) { ... } %>
根本不会向客户端输出ProductName。Javascript永远看不到它。 - Mehrdad Afshari看起来你只是在进行一些条件格式设置。如果你愿意,你可以在代码后台做一些这方面的工作。尝试使用标签并针对其执行一些逻辑操作。
<asp:Label id="lblProductName" runat="server" />
在您的代码后台,您可以像这样操作:
lblProductName.Text = ProductName;
lblProductName.Visible = CanRemove;
lblProductName.CssClass = "productLabel";
使用服务器端包含并不是一件可怕的事情,但如果您选择使用CodeBehind,可以使视图逻辑更加清晰分离。
我认为最好使用Literal控件,并在代码后台类的Page_Load或OnLoad方法中设置其Text属性。
protected void Page_Load(object sender, EventArgs e)
{
if (CanRemove)
{
myLiteral.Text = "<b>ProductName</b>"
}
}