How to save HTML to database and retrieve it properly
To framework 4.5, Using MVC 5, use @Html.Raw(WebUtility.HtmlDecode(item.ADITIONAL_INFORMAtION))
The rule of thumb is the following:
- Store in your database the RAW HTML without any encodings or sanitizings. A SQL server doesn't care if you store some string containing XSS code.
- When displaying this output to your page make sure that it is sanitized.
So:
[HttpPost, ActionName("Create")]
[ValidateAntiForgeryToken]
public ActionResult Create(Post model)
{
// store model.Data directly in your database without any cleaning or sanitizing
}
and then when displaying:
@Html.Raw(HtmlUtility.SanitizeHtml(Model.Data))
Notice how I used the Html.Raw helper here to ensure that you don't get double HTML encoded output. The HtmlUtility.SanitizeHtml
function should already take care of sanitizing the value and return a safe string that you could display in your view and it will not be further encoded. If on the other hand you used @HtmlUtility.SanitizeHtml(Model.Data)
, then the @
razor function would HTML encode the result of the SanitizeHtml
function which might not be what you are looking for.