0

I've tried using this:

Forum.Body = WebUtility.HtmlEncode(Forum.Body);

To encode the a string of text but it still doesn't encode the variable. What's wrong with the syntax?

1 Answer 1

1

Razor automatically HTML encodes by default as a security measure.

If you pass a Forum model object to the view and use razor all you will have to do is this:

@Model.Body

In the above it will encode the Body property by default.

This means that you shouldn't have to HTML encode from within the controller.

update

If you intend to output html you can either use:

 @Html.Raw(Model.Body)

Or add the following attribute to the property:

[AllowHtml]
public string Body { get; set; }
Sign up to request clarification or add additional context in comments.

2 Comments

For bonus points show @Html.Raw() usage, as I have an idea this is what the op might really want. Also consider HtmlString or whatever that class is that is handled automatically.
Thanks, good points. I have updated it. I will add HtmlString explanation when I get to a PC. @timothywalters

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.