Passing strings with Single Qoute from MVC Razor to JavaScript

后端 未结 2 1359
春和景丽
春和景丽 2021-02-07 04:13

This seems so simple it\'s embarrassing. However, the first question is when passing a value from the new ViewBag in MVC 3.0 (Razor) into a JavaScript block, is this the correct

相关标签:
2条回答
  • 2021-02-07 05:09

    Razor will HTML encode everything, so to prevent the ' from being encoded to ', you can use

    alert('@Html.Raw(ViewBag.str)');
    

    However, now you've got an actual ' in the middle of your string which causes a javascript error. To get around this, you can either wrap the alert string in double quotes (instead of single quotes), or escape the ' character. So, in your controller you would have

    ViewBag.str = "Hi, how\\'s it going?";
    
    0 讨论(0)
  • 2021-02-07 05:16

    Another solution to use JSON string:

    C#

    ViewBag.str = "[{\"Text\":\"Hi, how's it going?\"}]";
    

    Javascript

    var j = @Html.Raw(ViewBag.str);
    alert (j[0].Text); 
    
    0 讨论(0)
提交回复
热议问题