在 MVC Razor 视图中显示来自模型的 HTML 字符串 [英] Displaying HTML String from Model in MVC Razor View

查看:27
本文介绍了在 MVC Razor 视图中显示来自模型的 HTML 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型文件,它返回一个带有换行符 BR 标记的 HTML 字符串,但是如何在浏览器上显示该 HTML?问题在于换行符,标签本身显示在 UI 上

我试图将模型放在 Html.Raw(modelItem => item.Speaking) 中,但它从不工作,因为它需要一个字符串,并且无法将 lambda 表达式转换为类型字符串",因为它不是委托类型

以下是我尝试过的代码和注释.

@{string strTest = "<br/>第1行<br/>第2行<br>";@Html.Raw(strTest);//这可以正常工作并按预期显示@MvcHtmlString.Create(strTest);//这可以正常工作并按预期显示@Html.Raw(Html.DisplayFor(modelItem => item.Speaking));//这不起作用,它显示<br/>屏幕上@MvcHtmlString.Create(Html.DisplayFor(modelItem => item.Speaking).ToString());//这不起作用,它显示了<br/>屏幕上@Html.Raw(modelItem => item.Speaking)//这个抛出错误Cannot convert lambda expression to type string}

感谢任何帮助或建议.提前致谢!

解决方案

试试这个:

@(new HtmlString(stringWithMarkup))

你也可以创建一个 HTML 助手!:

@helper RawText(string s) {@(新的 HtmlString(s))}

I have a Model filed that returns an HTML string with line break BR tag, but How do I display that HTML on the browser ? The problem ins instead putting the line break, the Tag itself displaying on the UI

I tried to put the model within Html.Raw(modelItem => item.Speaking), but it never works as it expecting a string inside, and Cannot convert lambda expression to type 'string' because it is not a delegate type

Below is the code and comments what I've tried.

<div>
  @{          
     string strTest = "<br/>Line 1 <br/> Line 2<br>";
     @Html.Raw(strTest); //This works and display as expected
     @MvcHtmlString.Create(strTest); //This works and display as expected       

     @Html.Raw(Html.DisplayFor(modelItem => item.Speaking)); //This doesn't work, its show the <br />  on the screen     
     @MvcHtmlString.Create(Html.DisplayFor(modelItem => item.Speaking).ToString());   //This doent work, its show the <br />  on the screen  
     @Html.Raw(modelItem => item.Speaking) //This throw error Cannot convert lambda expression to type string                                     
    }

 </div>

Appreciate any help or suggestions. thanks in advance!

解决方案

Try this :

@(new HtmlString(stringWithMarkup))

and you can create a HTML helper too!:

@helper RawText(string s) {
    @(new HtmlString(s))
}

这篇关于在 MVC Razor 视图中显示来自模型的 HTML 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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