tags:

views:

51

answers:

4

Hello,

I am quite new to ASp.net MVC so it might be really trivial for you. Still, I have this question to ask : I want to display an image or not according to a booleean.

With classis asp.net, i was databinding the visible property with my boolean and then Hop, the trick was done. But here it doesn't work this way. I have browsed the web and found this way of dealing with it :

<%= Html.Image(this.ResolveUrl("~/attention.gif"),"dates invalid",myboolean) %>

with a Html hepler of this kind :

public static string Image(this HtmlHelper helper,
                                    string url,
                                    string altText,
                                    bool IsVisible)
        {
            string returnvalue = string.Empty;
            if (IsVisible)
            {
                 TagBuilder builder = new TagBuilder("image");
                 builder.Attributes.Add("src", url);
                 builder.Attributes.Add("alt", altText);
                 builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
                 returnvalue = builder.ToString(TagRenderMode.SelfClosing);
            }
            return returnvalue;
        }

Am I doing right or is there something easier I didn't get?

+2  A: 

How about:

<% if (myboolean) { %>
  <img src="<%= Url.Content( "~/attention.gif" ) %>" alt="dates invalid" />
<% } %>

This works pretty well for a one-off. If you needed to do this frequently, then investing in an HtmlHelper extension seems reasonable, though you could use the one from MVC Futures and simply use an Html attribute of style="display: none;" and get the same effect without writing your own.

tvanfosson
+2  A: 

How about this?

<% if (myBoolean) { %>
    <%= Html.Image("myUrl", "altText") %>
<% } %>
rmacfie
+1  A: 

This code does not create a hidden element. While that might be exatly what you need, you should be aware of the implication that you can't use JS on the client side to flip it back to visible if your app logic dictates so.

Having special HtmlHelper just to output an image based on a boolen seems a bit of overkill. How many images you will have that need to be shown/hidden in this way? If it's only one, just consider something like this in your view:

<% if (myboolean) { %>
    <img src="<%= this.ResolveUrl("~/attention.gif") %> alt="dates invalid" />
<% } %>
Franci Penov
+1  A: 

It seems nice, but I would change

this.ResolveUrl("~/attention.gif")

to

HttpContext.Current.Server.MapPath(url)

in helper method. This way you could call

<%= Html.Image("~/attention.gif","dates invalid",myboolean) %>

Looks nicer and you don't have to repeat ResolveUrl.

LukLed