tags:

views:

95

answers:

2

I have this cute little progress bar looking thing in a dashboard page. Once it is started up, it updates itself every minute via ajax, javascript, blah, blah. Since some of my viewers are looking at it on older Blackberries, I normally figure out how big the bar should be for the initial rendering server-side, and draw the page accordingly, then let the javascript take over after that, on those viewers that have it.

The old code, plain old ASP.NET has an asp:Label in the page where the img tag goes, and on the server I cat together the whole thing. As I refactor to an MVC way of looking at things, I thought how wonderful it would be to only write the width style attribute of the image on the server. The code on the page would be a good deal more understandable that way.

But it doesn't work. Example:

<img src="/content/images/blue_1px.png" class="productionBar_variableBar" 
style="width: <% =dbd["ThisShiftProduction_variableBar"] %>;"/>

Unfortunately, Visual Studio doesn't seem to recognize the <% %> escape inside of the quoted style attribute.

Any suggestions?

Siggy

+2  A: 

Have you tried doing this instead

<img src="/content/images/blue_1px.png" class="productionBar_variableBar" style='width: <% =dbd["ThisShiftProduction_variableBar"] %>;'/>

Notice the single quotes instead of the double quotes in the style attribute

dswatik
Thank you, dswatik, that did it, though I do observe that VS2k8 still doesn't understand what is going on and highlight things properly.
+2  A: 

The simplest way - creating HtmlHelper extension:

public static class Html
{
    public static string ProgressBar(this HtmlHelper html, int width)
    {
        StringBuilder sb = new StringBuilder();

        sb.AppendFormat("img src=\"/content/images/blue_1px.png\" class=\"productionBar_variableBar\" style=\"width: {0};\" />", width);

        return sb.ToString();
    }

    // OR

    public static string ProgressBar(this HtmlHelper html, int width, string src, string cssClass)
    {
        TagBuilder tagBuilder = new TagBuilder("img");
        tagBuilder.AddCssClass(cssClass);
        tagBuilder.MergeAttribute("style", "width: " + width.ToString());

        string srcUrl = new UrlHelper(html.ViewContext.RequestContext).Content(src);

        tagBuilder.MergeAttribute("src", srcUrl);

        return tagBuilder.ToString(TagRenderMode.Normal);
    }
}

Using it:

<%= Html.ProgressBar(dbd["ThisShiftProduction_variableBar"]) %>

<!-- OR -->

<%= Html.ProgressBar(dbd["ThisShiftProduction_variableBar"], "~/content/images/blue_1px.png", "productionBar_variableBar") %>
eu-ge-ne
And a very clean and reusable method.
Daniel A. White
Thanks to you, as well, eu-ge-ne. I shall be trying this one on for size to see if I like it.Cheers.