2

Is it possible to use an attribute in the viewmodel to specify for razor to render a string without html encoding?

edit: What I was asking was if it was possible to add an attribute in the model and have it modify the data representation (, like how you can add [Disable], [Layout(...)], [Required], etc.) - in such a way that it would make the html in a string render.

3 Answers 3

1

Not that I know of, but it appears that you can change the datatype from a string to an HTMLString. If you use an HTMlString, it should render the HTML in the string.

See Always output raw HTML using MVC3 and Razor

The second response in that thread shows a possible way of using an attribute to display raw html.

Sign up to request clarification or add additional context in comments.

Comments

1

Try Html.Raw(yourstring)

This should help.

Comments

0

MVC by default outputs a string as plain string, not HTML.

e.g. in your Action:

public ActionResult Test()
{
    var model = new TestViewModel(); // your view model
    model.Message = "<b>hello</b>";
    return View(model);
}

your View:

@model MyProject.TestViewModel

<div>
    @Model.Message
</div>

This will render as:

<b>hello</b>

If you want to actually render it as HTML, you need to change the above to this:

@MvcHtmlString.Create(Model.Message)

Alternatively, you could create an extension to make it nicer:

    public static MvcHtmlString ToMvcHtmlString(this String str)
    {
        if (string.IsNullOrEmpty(str))
            return MvcHtmlString.Empty;
        else
            return MvcHtmlString.Create(str);
    }

So then to render a string as HTML, in your View, you could write:

@Model.Message.ToMvcHtmlString()

If this is not what you're after, you should provide us with an example of where your code is falling over.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.