<div class="panel-body">@Html.Raw(item.PostContent.Substring(0, 200))</div>
上面的代码产生错误!当我将鼠标悬停在item.PostContent
上时,它告诉我它是字符串!
这段代码:
<div class="panel-body">@Html.Raw(item.PostContent)</div>
工作正常并显示整个帖子内容! 我该怎么做才能解决这个问题? 我想得到一个帖子的前200个字符并将它们显示为摘录。
答案 0 :(得分:2)
下面的内容可能很有用。
public static class HtmlPostExtensions
{
public static IHtmlString Post(this HtmlHelper helper, string postContent)
{
string postStr = postContent;
if (postStr.Length > 200)
{
postStr = postStr.Substring(0, 200);
}
return MvcHtmlString.Create(postStr);
}
}
可以用作
@Html.Post(item.PostContent)
答案 1 :(得分:1)
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
答案 2 :(得分:1)
检查长度是否大于200并截断否则只使用长度
<div class="panel-body">@Html.Raw(item.PostContent.Substring(0, item.PostContent.Length > 200 ? 200 : item.PostContent.Length))</div>
如果可能,您应该在操作方法中执行此操作,然后再将其传递给视图。它会使剃刀代码/标记更清洁。可以在投影模型[思考LINQ]
时完成帖子内容以html格式显示。因此,首先我需要得到平原 该html源文本然后得到前200个字符。任何 溶液
您必须首先解析操作中的内容以获取所需内容,然后根据需要进行截断。不要为视图添加太多复杂性。
您可以使用Html Agility Pack( NuGet HtmlAgilityPack 1.4.9.5 )解析内容并提取该html的普通测试,然后获取前200个字符
var html = new HtmlDocument();
html.LoadHtml(item.PostContent);
var root = html.DocumentNode;
var postContent = root.InnerText;
var postLength = postContent.Length;
var truncatedContent = postContent.Substring(0, postLength > 200 ? 200 : postLength);
同样,这应该在将项目发送到视图之前完成。