ASP.NET MVC Razor 视图中的 Html.Raw() [英] Html.Raw() in ASP.NET MVC Razor view

查看:28
本文介绍了ASP.NET MVC Razor 视图中的 Html.Raw()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@{int count = 0;}@foreach(Model.Resources 中的 var 项){@(count <= 3 ? Html.Raw("

").ToString() : Html.Raw(""))//一些代码@(count <= 3 ? Html.Raw("</div>").ToString() : Html.Raw(""))@(计数++)}

此代码部分无法编译,出现以下错误

Error 18 无法确定条件表达式的类型,因为在 'string' 和 'System.Web.IHtmlString' 之间没有隐式转换 d:ProjectsIRC2011_HGIRC2011ViewsHome\_AllResources.cshtml 2124 IRC2011

我必须做什么?

解决方案

Html.Raw() 返回IHtmlString,而不是普通的string.因此,您不能将它们写在 : 运算符的相反侧.删除 .ToString() 调用

@{int count = 0;}@foreach(Model.Resources 中的 var 项){@(count <= 3 ? Html.Raw("

"): Html.Raw(""))//一些代码@(count <= 3 ? Html.Raw("</div>") : Html.Raw(""))@(计数++)}

顺便说一下,返回IHtmlString是MVC识别html内容的方式,不对它进行编码.即使没有引起编译器错误,调用ToString()也会破坏Html.Raw()

的含义

@{int count = 0;}
@foreach (var item in Model.Resources)
{
    @(count <= 3 ? Html.Raw("<div class="resource-row">").ToString() : Html.Raw("")) 
    // some code
    @(count <= 3 ? Html.Raw("</div>").ToString() : Html.Raw("")) 
    @(count++)

}

This code part does not compile, with the following error

Error   18  Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.Web.IHtmlString'   d:ProjectsIRC2011_HGIRC2011ViewsHome\_AllResources.cshtml  21  24  IRC2011

What I must I do?

解决方案

Html.Raw() returns IHtmlString, not the ordinary string. So, you cannot write them in opposite sides of : operator. Remove that .ToString() calling

@{int count = 0;}
@foreach (var item in Model.Resources)
{
    @(count <= 3 ? Html.Raw("<div class="resource-row">"): Html.Raw("")) 
    // some code
    @(count <= 3 ? Html.Raw("</div>") : Html.Raw("")) 
    @(count++)

}

By the way, returning IHtmlString is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString() would destroy meaning of Html.Raw()

这篇关于ASP.NET MVC Razor 视图中的 Html.Raw()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆