Remove HTML tags from String in MVC View Page

In this section we'll show your content without any HTML tag. After following these below steps you will get your string value without HTML tags.

Step-1: 
In MVC view page (.cshtml), write this below code to the top of the view.
 @using System.Text.RegularExpressions;

@helper StripHTML(string input)
{
    if (!string.IsNullOrEmpty(input))
    {
        input = Regex.Replace(input, "<.*?>", String.Empty);
        <span>@input</span>
    }
}

e.g: If your string value content "<p> Welcome <p>" HTML tags, For to show your content without any formatting here we are using this Regex.Replace(input, "<.*?>", String.Empty) to strip all of Html tags from your string.

Step - 2: 
Here we will use that above helper function in that same view page. Like:

<div>@StripHTML(item.description.ToString())</div>

----------------------------------------------------------------------------------

For Displaying that string value with HTML tags in razor view then follow below code:

<div>@Html.Raw(item.description)</div>


Post a Comment

0 Comments