SteinTech
SteinTech

Reputation: 4068

how to add a TagBuilder to View when loading

I'm trying to add an option tag using TagBuilder. But I can't figure how to write the tagbuilder to the View.

Code:

@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);
}

Upvotes: 1

Views: 149

Answers (3)

cherry
cherry

Reputation: 722

I'm migrating a site to .NET6 and the solution there is to use the @ followed by the TagBuilder object's name : -

@foreach (IActivityType at in _data.Context.ActivityType)
{
    TagBuilder opt = new TagBuilder("option");
    
    // ...

    @opt // <-- This renders opt to the View.
}

Upvotes: 0

SteinTech
SteinTech

Reputation: 4068

So ended up with a great little solution with an IHtmlContent extension that return a tag as 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());

I called the extension method for ToZstring() to avoid naming issues with ToString()

Upvotes: 0

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30625

Try

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

PS: You may need to use SetInnerText() with option tag

Please also keep in mind that the preferable approach is to create custom HTML Helper and use it accordingly. Check This Link

Upvotes: 2

Related Questions