-2

I have a field in my model that contains static html (eg <br />).

When attempting to populate a div using jQuery using $('#myField').html(fieldval), the browser throws and error that it received an Invalid or Unexpected token. Is it possible to use jQuery to populate a div with html content?

$('#myDiv').html(@Html.Raw(modelvalue));
$('#myDiv').html(modelvalue);
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Chives
  • 75
  • 1
  • 12
  • Is that @Html.Raw Razor syntax? – Train Jan 30 '19 at 21:25
  • 1
    If you’re using server side variable, you need to wrap it in quotes. – Terry Jan 30 '19 at 21:25
  • Use .text() method of jquery as in this [example](https://stackoverflow.com/questions/16019621/fill-div-with-html-using-javascript-jquery) – Ahmet Jan 30 '19 at 21:26
  • Why not look at what the Razor output? View source in the browser. You'll see you have invalid html, eg `$('#myDiv').html(
    )` when it should obviously be `$('#myDiv').html("
    ")`. `@Html.Raw` will output as-is, while `@Model.Value` will escape for you (the opposite of how it worked in asp.net)
    – freedomn-m Jan 30 '19 at 22:16

1 Answers1

1

You should be careful to prevent xss when introducing html into the page.

That said, to what what you are asking, make sure to quote the model value, as jQuery expects a string. This will work.

$('#myDiv').html('@(new HtmlString(modelvalue))');

However, you should not.

You should instead use either a WYSIWYG editing library or whitelist accepted html from the user prior to inserting raw HTML. If it is not user based, then you should create a separate view with its own html structure, and then populate that with sanitized values; and then insert that view instead of the raw string.

If it is the case that you are somehow writing to the response stream directly, and the string produced is sanitized then you probably wouldn't have asked this rather basic question, so I am ruling that out.

Travis J
  • 81,153
  • 41
  • 202
  • 273