我正在尝试使用TagBuilder添加一个选项标签。但是我不知道如何将标签生成器写到视图中。
代码:
@foreach (IActivityType at in _data.Context.ActivityType)
{
TagBuilder opt = new TagBuilder("option");
opt.Attributes.Add("value", at.Id.ToString());
if (at.Id.Equals(activity.ActivityTypeId))
{
opt.Attributes.Add("selected", "selected");
}
@Html.Raw(opt);
}发布于 2019-02-15 07:13:43
试一试
@Html.Raw(opt.ToString(TagRenderMode.Normal));PS:您可能需要使用带有option标签的SetInnerText()
还请记住,更好的方法是创建自定义HTML Helper并相应地使用它。Check This Link
发布于 2019-02-15 14:45:30
所以最终得到了一个很好的小解决方案,它有一个IHtmlContent扩展,它返回一个html形式的标签。
public static string ToZtring(this IHtmlContent content, bool encode = false)
{
string result = default;
using (StringWriter sw = new StringWriter())
{
content.WriteTo(sw, HtmlEncoder.Default);
result = sw.ToString();
}
if (!encode)
{
result = HttpUtility.HtmlDecode(result);
}
return result;
}
TagBuilder opt = new TagBuilder("option");
opt.Attributes.Add("value", "demo");
@Html.Raw(opt.ToZtring());我调用了ToZstring()的扩展方法来避免ToString()的命名问题
https://stackoverflow.com/questions/54700487
复制相似问题