Where is Html.Image in ASP .NET MVC RC?

Its in MVC futures - which they are updating with each release.

RC2 futures is here : http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24142

Don't feel guilty about using something in 'futures'. Its not going anywhere - and even if it ever did you have access to the source.

You need to be slightly cautious about some things in futures (in case they disappear) but you can be pretty sure Image helper isnt going anywhere.


What's wrong with pure HTML?

<img src="" alt="" />

You could use the ViewData collection or model to populate the src attribute:

<img src="<%= ViewData["ImageSource"] %>" alt="" />

<img src="<%= ViewData.Model.ImageSource %>" alt="" />

Edit:

Regarding using relative urls (i.e. using the "~" character) in the path, change the above code to use ResolveUrl. For example:

<img src="<%= ResolveUrl(ViewData.Model.ImageSource) %>" alt="" />

Now we can return MvcHtmlString.

public static MvcHtmlString Image(this HtmlHelper helper, string url, string altText, object htmlAttributes)
        {
            TagBuilder builder = new TagBuilder("img");
            builder.Attributes.Add("src", url);
            builder.Attributes.Add("alt", altText);
            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
        }

usage in razor:

@Html.Image( Url.Content( "~/Content/images/img.png" ),
               "alt text",
               new { id = "myImage", border = "0" } )

Need to write your own or use the Url.Content() method to set the source attribute. Or you can use mine. :-)

public static class HtmlHelperExtensions
{

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

Usage:

<%= Html.Image( Url.Content( "~/Content/images/img.png" ),
               "alt text",
               new { id = "myImage", border = "0" } )
 %>

EDIT: Since I wrote this I've gone away from using it. I'll leave the answer here, though for posterity. While I think it, or the method from the Future assembly, is a reasonable choice, I find myself simply using the image tag with the url supplied by a UrlHelper. When I refactored my helpers into a standalone library, this one didn't make the cut. I'll re-evaluate if it makes it into the (non-futures) MVC library.

<img src="<%= Url.Content( "~/content/..." ) %>"
     alt="alt text"
     class="has-border" />

Tags:

Asp.Net Mvc