简体   繁体   English

截断ASP.NET MVC C#

[英]Truncate ASP.NET MVC C#

I'm displaying some content using the following bit of code: 我使用以下代码显示一些内容:

<% foreach ( var m in ViewData.Model) { %>

<div class="content">
<%= m.article %>
</div>

Which shows a news article from my database. 其中显示了我数据库中的新闻文章。 What I want to do is truncate the story to be smaller, how do would I do this? 我想做的是将故事截短,我该怎么做? Also the article column contains HTML tags such as <p> so therefore splitting up the article purely on character numbers would cause issues. 此外,文章专栏包含HTML标记(例如<p> ,因此,仅按字符数分割文章会引起问题。

Any ideas on where to start? 关于从哪里开始的任何想法? I'm new to MVC. 我是MVC的新手。

Thanks 谢谢

This is not a simple problem, but you can start by using the HtmlAgilityPack . 这不是一个简单的问题,但是您可以使用HtmlAgilityPack开始。

This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). 这是一个敏捷的HTML解析器,它构建了一个读/写DOM并支持纯XPATH或XSLT(您实际上不必了解XPATH或XSLT来使用它,不用担心...)。 It is a .NET code library that allows you to parse "out of the web" HTML files. 这是一个.NET代码库,可让您解析“网络外” HTML文件。 The parser is very tolerant with "real world" malformed HTML. 该解析器对“真实世界”格式的HTML十分宽容。 The object model is very similar to what proposes System.Xml, but for HTML documents (or streams). 对象模型与提出System.Xml的对象模型非常相似,但用于HTML文档(或流)。

Once you have your DOM in memory you can then extract or truncate elements in a way that will not break the DOM structure, eg, you can remove entire <p></p> nodes, or just truncate some fo the text within that node. 一旦将DOM存储在内存中,就可以以不破坏DOM结构的方式提取或截断元素,例如,可以删除整个<p></p>节点,或者仅截断该节点内的文本。

Do you have control over how articles are submitted? 您可以控制文章的提交方式吗? Perhaps you can ask for a short intro/summary. 也许您可以要求简短的介绍/摘要。 I believe WordPress does it. 我相信WordPress可以做到。

Or have the user insert a marker which signifies the end of intro/summary. 或者让用户插入一个标记,以表示简介/摘要的结尾。 something like: 就像是:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<!-- END INTRO -->
<p>Ut malesuada porttitor consectetur. </p>

You can display it without any consequences and still "split" the article programmatically. 您可以显示它而没有任何后果,并且仍然可以通过编程方式“拆分”文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM