2

I have a model passed into a cshtml view, and I'm trying to create a variable with a string from the model. The problem is that the string contains newlines, and when I create the variable, the newlines are not converted, and I end up with an Unterminated string constant error in the Javascript.

Currently I'm doing this:

var something = @Model.string;

How can I pass the model attribute so that new lines are preserved in the javascript variable?

dobber1611
  • 37
  • 3
  • At least related: http://stackoverflow.com/questions/3765122/escaping-a-double-quote-in-inline-c-sharp-script-within-javascript – T.J. Crowder Oct 31 '16 at 16:47
  • Almost certainly a duplicate of: http://stackoverflow.com/questions/36756829/pass-c-sharp-model-from-view-to-javascript – T.J. Crowder Oct 31 '16 at 16:48
  • you could try: Html.Raw(Model.string) http://stackoverflow.com/questions/11449782/how-to-create-a-javascript-string-in-razor – Reint Jan Hoiting Oct 31 '16 at 16:48
  • I'm finding these with [this search](/search?q=%5Bc%23%5D+%5Bjs%5D+%5Brazor%5D+pass+string+to+javascript). Remember it's important to search thoroughly before posting, not least because the answer is probably already here somewhere. – T.J. Crowder Oct 31 '16 at 16:49
  • @ReintJanHoiting: Part of that is probably missing, see the second link above. – T.J. Crowder Oct 31 '16 at 16:49
  • BTW, unless your using some sort of csjs, I would suggest using data-* attributes in CSHTML. This allows you to create a pattern that seperates the data from the code - e.g. `
    ` with JS `$('[data-something').data('something')`
    – James Haug Oct 31 '16 at 16:55
  • @ReintJanHoiting Using a `Html.Raw()` method isn't save (beause of XSS possibility attack). Just use `HttpUtility.JavaScriptStringEncode` method. – krypru Mar 20 '18 at 13:21

1 Answers1

0

It might help you:

var something = @:Model.ToString();
M. A. Cordeiro
  • 469
  • 8
  • 14