How to render html by passing as a controller string to the view?

Asked

Viewed 1,937 times

1

I have the following view:

    public ActionResult RelatorioEquipe()
    {
        ViewRelatorioEquipeDTO dto = new ViewRelatorioEquipeDTO();
        dto.LstUnidadeGerencial = negocio.Relatorio.ObterLstUg();
        dto.LstExercicios = new ExercicioNegocio().ObterExerciciosAtivos();

        dto.Html = "<img src=\"~/Imagens/LogoMetroRelatorio.png\" style=\"float: left\" />";        

        return View(dto);
    }

dto.Html is a string and when I refer to my page (cshtml):

<div class="logo">
    @Model.Html
</div>

The page naturally shows a string with this text.

The question is: how to instead of showing the string, render this html and display the image?

2 answers

2

Yes.

Implement in your project the following extension:

public static class ImageHelper
{
    public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText, string height, string style = "")
    {
        var builder = new TagBuilder("img");
        builder.MergeAttribute("src", src);
        builder.MergeAttribute("alt", altText);
        builder.MergeAttribute("height", height);
        if (style != "") builder.MergeAttribute("style", style);
        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
    }

    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.SelfClosing));
    }
}

Use:

@Html.Image("caminho/da/imagem", "texto alternativo", "altura", "float: left")

Or else:

@Html.Image("caminho/da/imagem", "texto alternativo", new { style = "float: left", border = "0" })

Don’t forget the using in View:

@using SeuProjeto.Extensions

Extensions is an example, but you can put the static class anywhere.

0


I found what I was looking for. I was able to render the html in Razor by just doing this:

<div class="logo">
    @Html.Raw(Model.Html)
</div>
  • Just so I understand: what is the need for you to mount HTML in your Controller?

  • It is because my PDF generator only generates PDF through view rendering. In my normal view I have a method that delivers JSON to the page via ajax and updates, but then the PDF cannot generate this update. I replicated the method and sent html back to a new view to generate the pdf.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.