【问题标题】:ASP.NET MVC Razor render without encoding using an attribute ie. data annotationASP.NET MVC Razor 渲染不使用属性进行编码,即。数据标注
【发布时间】:2014-10-19 22:25:16
【问题描述】:

是否可以在视图模型中使用属性来指定剃须刀在没有 html 编码的情况下渲染字符串?

edit:我要问的是是否可以在模型中添加一个属性并让它修改数据表示(例如如何添加 [Disable]、[Layout(...)]、[Required ] 等) - 以这样的方式使 html 在字符串中呈现。

【问题讨论】:

    标签: asp.net-mvc-3 razor


    【解决方案1】:

    据我所知,您似乎可以将数据类型从字符串更改为 HTMLString。如果您使用 HTMlString,它应该在字符串中呈现 HTML。

    Always output raw HTML using MVC3 and Razor

    该线程中的第二个响应显示了使用属性显示原始 html 的一种可能方式。

    【讨论】:

      【解决方案2】:

      试试Html.Raw(yourstring)

      这应该会有所帮助。

      【讨论】:

        【解决方案3】:

        MVC 默认将字符串输出为纯字符串,而不是 HTML。

        例如在你的Action:

        public ActionResult Test()
        {
            var model = new TestViewModel(); // your view model
            model.Message = "<b>hello</b>";
            return View(model);
        }
        

        你的View:

        @model MyProject.TestViewModel
        
        <div>
            @Model.Message
        </div>
        

        这将呈现为:

        <b>hello</b>
        

        如果你想真正将它呈现为 HTML,你需要将上面的内容更改为:

        @MvcHtmlString.Create(Model.Message)
        

        或者,您可以创建一个扩展以使其更好:

            public static MvcHtmlString ToMvcHtmlString(this String str)
            {
                if (string.IsNullOrEmpty(str))
                    return MvcHtmlString.Empty;
                else
                    return MvcHtmlString.Create(str);
            }
        

        那么要将字符串呈现为 HTML,在您的 View 中,您可以编写:

        @Model.Message.ToMvcHtmlString()
        

        如果这不是您所追求的,您应该向我们提供您的代码失败的示例。

        【讨论】:

          猜你喜欢
          • 2011-05-03
          • 1970-01-01
          • 1970-01-01
          • 2012-05-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多