Rahul Pawar
Rahul Pawar

Reputation: 1036

How to remove html tags from string in view page C#

How to strip html tags from string in listing page in c# I have tried Regex.Replace(inputHTML, @"<[^>]+>|&nbsp;", "").Trim(); but this is not working in html view page may be this only work in controller.

This is my action :

public ActionResult Index()
        {
            string AuthRole = "1,2,3";
            ApplicationUser chkuser = common.CheckIsAuthorize(AuthRole);
            if (chkuser != null)
            {
                var data = db.Page.ToList();
                return View(data);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

This is my view :

foreach (var item in Model)
{
<tr>
    <td>@i</td>
    <td>@item.Title</td>
    <td>@item.Message</td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.Id })
    </td>
</tr>
i++;
}

My listing look like below :

enter image description here

Upvotes: 4

Views: 22382

Answers (3)

Harikrishna
Harikrishna

Reputation: 63

Use mvc html helpers

@Html.Raw(item.Message)

Upvotes: -2

er-sho
er-sho

Reputation: 9771

If you want to show your content without any formatting then you can use this Regex.Replace(input, "<.*?>", String.Empty) to strip all of Html tags from your string.

1) Add below code to top of view (.cshtml).

@using System.Text.RegularExpressions;

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

2) Use the above helper function like

<td>@StripHTML(item.Message)</td>

Upvotes: 21

Ashiq Hassan
Ashiq Hassan

Reputation: 428

Replace

<td>@item.Message</td>

with

<td>@Html.Raw(item.Message)</td>

this may help you to display html in razor view

Upvotes: -5

Related Questions