首页 > 解决方案 > 如何在 asp.net 中将字符串呈现为 html?

问题描述

将表中的输入字段字符串转换为输入字段?

<%= HttpUtility.HtmlDecode((string)objRow["Post"]) %>

在视图结束

<%= HttpUtility.HtmlDecode(GetUsersList())%>

Cs 文件中的代码

foreach (DataRow dtRow in ds.Tables[0].Rows)
{
    string userpk = Convert.ToString(dtRow["user_pk"]);
    string usertypecd = Convert.ToString(dtRow["user_type_cd"]);
    string firstname = Convert.ToString(dtRow["first_name"]);
    string lastname = Convert.ToString(dtRow["last_name"]);
    string active = Convert.ToString(dtRow["active_ind"]);
    if (active == "true")
    {
        active = "< input type = 'checkbox' class='editor-active' disabled='disabled' checked='checked'>";
    }
    else {
        active = "< input type = 'checkbox' class='editor-active' disabled='disabled'>";
    }
    string phoneno = Convert.ToString(dtRow["phone_no"]);
    string phone_ext = Convert.ToString(dtRow["phone_ext"]);
    string email = Convert.ToString(dtRow["email"]);

    content += "<tr><td>"+ usertypecd+ "</td><td>" + firstname + "</td><td>" + lastname + "</td><td>" + active + "</td><td>" + phoneno + "</td><td>" + phone_ext + "</td><td>" + email + "</td><td></td></tr>";        
}

return content;

结果图像:

在此处输入图像描述

标签: c#asp.net

解决方案


如果您的意思是 Asp-WebForms,您可以使用属性System.Web.Label中的 html 文本创建一个。Text如果您将控件添加到页面,这将呈现为 HTML。

或者,您可以将文本转储到受保护/公共属性中,然后<%= YourPropertyNameHere %>将文本原样转储到页面中。

我个人建议您构建您的 Web 控件而不是字符串操作。例如,创建一个System.Web.Panel,然后根据需要将您的 html 控件添加到其中。

var pnl = new Panel();
var cb = new CheckBox();
cb.Enabled = (active == "true");
cb.Checked = cb.Enabled;
cb.CssClass = "editor-active";
pnl.Controls.Add(cb);

SomePanelInFrontCode.Controls.Add(pnl);

推荐阅读