我正在实现类似于博客引擎的功能,在条目页面上,我希望看到我的帖子列表,以及每个帖子的标题和正文的一小段内容。该正文内容是HTML,并且作为字符串存储在数据库中,因此仅显示它的子字符串是不够的,因为它可能会破坏HTML结构。我猜算法是:将字符串呈现为HTML并仅提取其前X个字符。这个问题有什么解决办法吗?
这是一个工作示例,如下所示:
视图:
@model IEnumerable<Post>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Body)
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Body)
</td>
</tr>
}
</tbody>
</table>
控制器:
public IActionResult Test()
{
var model = new List<Post>()
{
new Post(){ Title="asp.net core mvc",Body="<html><div><h1>The Model-View-Controller (MVC) architectural pattern separates an application into three main groups of components: Models, Views, and Controllers. This pattern helps to achieve separation of concerns. Using this pattern, user requests are routed to a Controller which is responsible for working with the Model to perform user actions and/or retrieve results of queries. </h1></div></html>"},
new Post(){Title="asp.net core razor pages",Body="<html><div>Razor Pages is designed to make common patterns used with web browsers easy to implement when building an app. Model binding, Tag Helpers, and HTML helpers all just work with the properties defined in a Razor Page class.</div></html>"}
};
foreach(var item in model)
{
item.Body= Regex.Replace(item.Body, @"<[^>]+>| ", String.Empty);
item.Body= item.Body.AsSpan(0, 30).ToString()+"...";
}
return View(model);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句