tags:

views:

83

answers:

3

I came across some code like this:

public string IsAdmin()
{
    string style = "";

    if(EditUserName == "")
    {
        style = "visibility:hidden;display:none";
    }
    return style;
}

Then in the html, I see something like this:

 <table style='<%= IsAdmin() %>'>
 </table>

The above doesn't seem the best way to do this. Is there a more efficient and alternative way to set the style of html elements programmatically.

+2  A: 

I'll start it off by saying that it's generally a bad practice to set inline styles on elements -- especially on server-side code.

Style should generally be set through external style sheets.

When manipulating the DOM on the client-side, there are a number of acceptable ways of setting an element's style. Generally, it's efficient for coders to use a library like jQuery.

bigmattyh
+1 It would be much better to follow this advice and use CSS classes. Then determine at server-time whether to include user.css or admin.css and re-style as needed.
Will Bickford
He may still need this technique in order to set the CSS class, which could be determining whether an item should be initially visible.
John Fisher
+1. Embedding inline CSS is just as evil as the old-school FONT tag. Don't do it. Instead, create a separate CSS file with a rule for "table.admin", and set the table CLASS attribute to "admin" based on your logic. Keep logic and design concerns separate.
richardtallent
The whole asp.net domain is so weird and ... wrong ... for writing webapps.
bigmattyh
I 100% agree with the inline styles
Xaisoft
+2  A: 

If you use this arrangement:

<table runat="server" ID="tableElement">
</table>

then, you can do something like this:

HtmlTable table = (tableElement as HtmlTable);
table.Style.Add(HtmlTextWriterStyle.Display, "none");
table.Style.Add(HtmlTextWriterStyle.Visibility, "hidden");

Edit

In light of the other suggestions, you would instead use this technique like this:

table.Style.Add("class", "whatever");
John Fisher
+3  A: 

To me it looks like what you really want is visibility based on permissions not really styles, why not do this:

Markup:

<table runat="server" visible='<%= IsVisible() %>'>
</table>

Code-behind:

protected bool IsVisible()
{
    bool result= true;

    if(EditUserName == string.empty)
    {
        result= false;
    }
    return result;
}
rick schott
That seems better.
Xaisoft
This could cause a negative effect if Javascript is planning on dynamically showing the table later on, because setting the table to not Visible prevents the HTML from writing to the browser
bendewey
@bendewey - Can you explain a bit further? Do you mean setting the table's visibility through it's style attribute or the visible attribute?
Xaisoft
The Visible attribute when using runat="server" will not render the HTML. (ie. you javascript won't find the element because it won't exist)
bendewey