views:

353

answers:

2

Hi, I am picking my way through some c# code I inherited, and trying to show an image within a link;this is the line that works, and show's the image, but I need to wrap this in a link.

Response.Write(Html.PropImage(item.MainImage.ImageUrl095, item.AccomName));

I noticed later on there is a link element, so I thought I could copy this (as it is the right link I need) and wrap it around the HTML.PropImage line.Like this

Html.PropRefLink(item.AreaName, item.AccomName, item.AccomCode, Html.PropImage(item.MainImage.ImageUrl095, item.AccomName), (string)ViewData["PDate"], (string)ViewData["PDuration"], (string)ViewData["PSleeps"]);

I removed the response.write as it was breaking the page, how can I that html.propimage to render within the link ?

Thanks

A: 

Since the function only allows link text (or so it seems from your comment) your best bet would be to use flat HTML. Change the link text to:

"<img src=\"" + item.MainImage.ImageUrl095 + "\" alt=\"\" />"

This will render a standard HTML image tag within your link and should work as expected.

AverageAdam
hi, thanks for the tip there, I reworked the link a little using your example and did thisResponse.Write("<a href=\"\">"+Html.PropImage(item.MainImage.ImageUrl095, item.AccomName)+"</a>");this seems to work - not sure if it's the correct practice though ?
ivor
It is really hard to judge without knowing what the PropImage or PropRefLink methods actually do. Reponse.Write, however, is generally to be avoided if possible.
AverageAdam
no! Create your own helper extension method using the tutorial i provided. The existing helper methods clearly dont do what you want so just create your own (this is better practice than above) also response.write(Html.MyImageLink("image","url")) should be done in code tags like this really: <%= Html.MyImageLink("image","url") %>
Mark
A: 

I would suggest that you are best off creating your own Html Helper Extension Method to create an img element wrapped within the link element. you can use the StringBuilder class for this

HTMl Helper Tutorial

Basic Example:

using System;
using System.Web.Mvc;
using System.Text;

namespace MvcApplication1.Helpers
{
    public static class ImageHelpers
    {
        public static string ImageLink(this HtmlHelper helper, string imagepath, string url)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<a href=\"" + url + "\">");
            sb.Append("<img src=\"" + imagepath + "\" />");
            sb.Append("</a>");
            return sb.ToString();
        }
    }
}

Then you would call your extension method within your view as follows:

<%= Html.ImageLink("imagepath","theurl") %>
Mark