Assuming your model contains a public string MyHtml { get; set; }
property, then to display the results in a view, use
@Html.Raw(Model.MyHtml)
To identify if the posted value contains any <script>
tags and/or to remove them from the value, use a html parser such as Html Agility Pack. For example in your POST method, you could add a ModelStateError
and return the view
public ActionResult Save(MyModel model)
{
if (HasScripts(model.MyHtml)
{
ModelState.AddModelError("MyHtml", "The html cannot contain script tags");
}
if (!ModelState.IsValid)
{
return View(model);
}
// save and redirect
}
Where HasScripts()
is
public bool HasScripts(string html)
{
HtmlDocument document = new HtmlDocument();
document.LoadHtml(html);
HtmlNode root = document.DocumentNode;
return root.Descendants("script").Any();
}
Alternatively, if you want to just remove them before saving, you could use the following method
public string RemoveScripts(string html)
{
HtmlDocument document = new HtmlDocument();
document.LoadHtml(html);
HtmlNode root = document.DocumentNode;
IEnumerable<HtmlNode> scripts = root.Descendants("script");
for(int i = 0; i < scripts.Count(); i++)
{
HtmlNode script = scripts[i];
script.Remove();
}
return scripts.Any() ? document.ToString() : html;
}
and use it as
model.MyHtml = RemoveScripts(model.MyHtml);
Note: If you are tempted to use a regex for this, I recommend reading Regular Expression for Extracting Script Tags.
You might also want to consider checking for other potentially malicious elements such as <embed>
, <iframe>
, <form>
etc