How can I show a viewbag as html?

前端 未结 5 1546
独厮守ぢ
独厮守ぢ 2021-02-03 21:33

OK, quite new to ASP.Net MVC, so I\'m sorry if this is a silly question, but how do I go about showing the values of a ViewBag as HTML. For Example, if ViewBag.SomeMessage conta

相关标签:
5条回答
  • 2021-02-03 22:11

    Everyone is correct in the use of @Html.Raw() but I want to point out to be careful with this, as it can make your site susceptible to XSS vulnerabilities.

    I would combine the @Html.Raw(ViewBag.SomeMessage) with Microsoft's Anti-XSS Library to make sure you do not introduce any vulnerabilities from this.

    Edit: The advantage of the Anti-XSS library (if you haven't looked at it) is it has a whitelist of approved markups (such as <b>, <h3>, etc..) so that only approved markups will be un-encoded.

    Edit2: Here's an example of how this is done.

    0 讨论(0)
  • 2021-02-03 22:19

    You would use the Raw method:

     @Html.Raw(ViewBag.SomeMessage)
    
    0 讨论(0)
  • 2021-02-03 22:30

    I think you can do something like this:

    @Html.Raw(ViewBag.SomeMessage)
    
    0 讨论(0)
  • 2021-02-03 22:35

    put data to ViewBag as a HTML-encoded string that should not be encoded again.

    ViewBag.myBag = MvcHtmlString.Create(myCode ?? string.Empty);
    

    then use

    @ViewBag.myBag
    

    The documentation for MvcHtmlString.

    0 讨论(0)
  • 2021-02-03 22:38
    @Html.Raw(ViewBag.SomeHtmlProperty)
    

    This being said, here's my disclaimer: DON'T USE ViewBag. Use strongly typed views and view models. ViewBag/ViewData is like cancer for an ASP.NET MVC application.

    0 讨论(0)
提交回复
热议问题