简体   繁体   中英

ASP.NET MVC C# How to use this function

I have the following function inside my HomeController class:

public class HomeController : Controller
    {

        public string Strip(string text)
        {
            return Regex.Replace(text,@"<(.|\n)*?>",string.Empty);
        }

On my view I have the following to show an article from a database:

<%= item.story %>

A typical article will look like the following:

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea <em>commodo consequat</em>.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

As you can see the text has HTML tags throughout. What I would like to do is use my Strip function with item.story to remove those HTML tags. After that I would like to truncate the remaining text into 20 WORDS .

So I'll end up with something along the lines of:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua dolore... with no HTML tags and only about 20 WORDS long .

How do I do this with my current code? Is the HomeController the correct place for the Strip function to be? Thanks

Controllers should hold Actions. What you're looking for is probably an extension method, one that you can call on your string.

You'll probably need two extensions, one to strip out HTML tags, the other to create the 20-word-short-format version of your paragraph.

UPDATE To answer your question...

You can create a new class (say ParagraphExtension.cs) and put your string extensions in this class:

namespace myApp.Util.Extensions
{
      public static class ParagraphExtension
      {
           public static string RemoveHTMLTags(this string content)
           {
                   // insert code
           }

           public static string ShortFormParagraph(this string content)
           {
                   // insert code
           }
       }
}

In your view, you can then import the namespace in which this class is found:

<%@ Import Namespace="myApp.Util.Extensions" %>

Finally, you can call the extensions from within the view:

<%= item.story.RemoveHTMLTags().ShortFormParagraph() %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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