代码之家  ›  专栏  ›  技术社区  ›  SteinTech

如何在加载时添加要查看的标记生成器

  •  0
  • SteinTech  · 技术社区  · 7 年前

    代码:

    @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);
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Derviş Kayımbaşıoğlu    7 年前

    尝试

    @Html.Raw(opt.ToString(TagRenderMode.Normal));
    

    PS:您可能需要使用 SetInnerText() 具有 option

    还请记住,最好的办法是 创建自定义HTML帮助程序 并相应地使用它。 Check This Link

        2
  •  0
  •   SteinTech    7 年前

    所以最终得到了一个很好的小解决方案,它有一个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());
    

    推荐文章