0

I need my app to send a confirmation email to a user. I have used the following method to render the view as a string:

    public string RenderViewToString<T>(string viewPath, T model)
    {
        using (var writer = new StringWriter())
        {
            var view = new WebFormView(viewPath);
            var vdd = new ViewDataDictionary<T>(model);
            var viewCxt = new ViewContext(ControllerContext, view, vdd, new TempDataDictionary(), writer);
            viewCxt.View.Render(viewCxt, writer);
            return writer.ToString();
        }
    }

which I got from here. It works great, however my images aren't being included. I'm using:

<img src="<%:Url.Content("~/Resource/confirmation-email/imageName.png") %>"

which is giving me

http://resource/confirmation-email/imageName.png

This works fine when viewing the page on the site, however the image links don't work in the email.

I need it to give me me:

http://domain.com/application/resource/confirmation-email/imageName.png

I've also tried using:

VirtualPathUtility.ToAbsolute()
Community
  • 1
  • 1
Alex
  • 1,042
  • 3
  • 13
  • 32

2 Answers2

1

This is what I used on a site recently:

public static string ResolveServerUrl(string serverUrl, bool forceHttps = false, bool getVirtualPath = true)
{
    if (getVirtualPath)
    serverUrl = VirtualPathUtility.ToAbsolute(serverUrl);

    if (serverUrl.IndexOf("://") > -1)
    return serverUrl;

    string newUrl = serverUrl;
    Uri originalUri = System.Web.HttpContext.Current.Request.Url;
    newUrl = (forceHttps ? "https" : originalUri.Scheme) + "://" + originalUri.Authority + newUrl;
    return newUrl;
}

I could then use it to generate Absolute urls by doing Core.ResolveServerUrl("~/Resource/confirmation-email/imageName.png"); (assuming you wrap the static function in a class named Core)

HTH

Gavin
  • 6,284
  • 5
  • 30
  • 38
0

There isn't a way to do this. You can add the following extension method.

using System.Web.Mvc;

public static class UrlHelperExtensions
{
    public static string ToAbsoluteUrl(this UrlHelper helper, string relativeUrl) {
        if (Request.IsSecureConnection)
            return string.Format("https://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
        else
            return string.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
    }
}

Which you can then call like so

<img src="<%:Url.ToAbsoluteUrl("~/Resource/confirmation-email/imageName.png") %>" ...
Jaimal Chohan
  • 8,530
  • 6
  • 43
  • 64
  • This is just the same as using Url.Content... The email needs the absolute URI to know where to serve the images from. – Gavin May 24 '12 at 15:40