Andrus
Andrus

Reputation: 27919

How to render absolute URL in asp .net mvc 2 view

In AS:NET / Mono MVC2 method below form Render a view as a string is used to create html e-mail bodies.

Partiil view Order.ascx contains images like

    <img width='20%' alt='' src='<%= Url.Action("Logo", "Store")%>' />

In Emails those images appear without site address like /Store/Logo and thus images do not appear. How to force image links to appear with absolute addresses like htttp:/Mysite.com/Store/Logo or add site base address to html email body is this helps.

ASP.NET / Mono MVC2 , .NET 3.5, jquery, jquery ui are used.

Controller Action method:

        var s = RenderViewToString<OrderConfirm>("~/Views/Checkout/Order.ascx", order);

public class ControllerBase : Controller
{
    protected string RenderViewToString<T>(string viewPath, T model)
    { 
        ViewData.Model = 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();
        }
    }

Upvotes: 1

Views: 2668

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Just use the proper overload:

<%= Url.Action("Logo", "Store", null, "http") %>

Since we've specified the protocol, the helper will generate an absolute url. Also if you don't want to hardcode it you could read it from the current request:

<%= Url.Action("Logo", "Store", null, Request.Url.Scheme) %>

Now this will work for both standard and HTTPS schemes depending on how the view is requested.

Upvotes: 3

Related Questions