user9647280
user9647280

Reputation:

Html Encoding/Decoding & Html.Raw

I hear that using HTML.Raw in Razor views is not recommended, and if so I have a problem.

I am using Entity Framework for interacting with my SQL DB. Also I am using SummerNote as an editor for the front end.

Now my view code is in @{ } block, which I believe does some encoding/decoding.

The scenario is that the user inputs some text in the SummerNote editor and applies some formatting (e.g making a word bold) and clicks saves. This will generate an HTML string and passes it to my controller:

<p>Test <b>string </b>with formatting.</p>

In the controller, I use HTML encode to encode:

customerData.Description = HttpUtility.HtmlEncode(summerNoteFieldData);

And then send it to DB. It looks like the following in DB:

&lt;p&gt;Test &lt;b&gt;string &lt;/b&gt;with formatting.&lt;/p&gt;

Then in the view when presenting it, I do:

<div class="summernote">@Html.Raw(@HttpUtility.HtmlDecode(@Model))</div>

So if I remove the Html.Raw, then I will see the above HTML string rather than formatted one.

Is this the safe and right way to go about this? Can it be improved?

Thank you for any help.

Upvotes: 1

Views: 10613

Answers (1)

SLaks
SLaks

Reputation: 887459

You should HTML encode as you print in your view (using @Model).

Do not encode or decode anywhere else; do not store encoded content in your database.

Upvotes: 3

Related Questions