使用 RegEx MVC 删除一些 HTML 标签

Remove some HTML Tags using RegEx MVC

我正在通过按下一个按钮来发送电子邮件,该按钮将整个视图转换为一个字符串,该字符串用作电子邮件的正文。

但是当邮件到达时,会出现“查看”按钮,我尝试用 RegEx 消除它,但它不起作用

如何从字符串中删除这些标签?

这是我的看法

@model IEnumerable<MvcInventory.TB_RS_PROD>
@{

}
<html>
<table class="table table-striped">
    <tr>
        <td>ID PRODUCT</td>
        <td>PRODUCT NAME</td>
        <td>QUIANTITY</td>
        <td>DATE</td>
        <td>STATUS</td>
        <td>EMAIL</td>
        <td>EMAIL 2</td>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
           <td>@item.IDPROD</td>
           <td>@item.PROD_NAME</td>
           <td>@item.QUANTITY</td>
           <td>@item.UPDATE_DATE</td>
           <td>@item.STATUS</td>
           <td>@item.EMAIL</td>
           <td>@item.EMAIL2</td>
        </tr>
    }
</table>
<button onclick="location.href='@Url.Action("SendEmail","Home")'">Send Email</button>
</html>

字符串编写器代码:

protected string RenderPartialViewToString(string viewName, object model)
{
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
}

终于调用了 RenderPartialViewToString

var htmlp = RenderPartialViewToString("~/Views/ActionApprovers/Action.cshtml", TempData["email-act"]);
var allowtag = new Regex(@"(</?[^(p|ol|ul|li|span|i|b|br|table|tr|td)]/?>)");
htmlp = allowtag.Replace(htmlp, "");

经过几次post我建议对要保留和删除的标签执行以下方法

    string acceptable = "p|a|tr|td|table|html"; //Tags that are a-okay to display
    string stringPattern = @"</?(?(?=" + acceptable + @")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:(["",']?).*??)?)*\s*/?>";
    htmlp = Regex.Replace(htmlp, stringPattern, "");