Search code examples
asp.net-corerazor-pagestag-helpersasp.net-core-tag-helpersasp.net-core-7.0

Optionally invoke tag helpers in Razor page


This select will be populated normally:

<select ... [email protected] asp-items=Model.Products>
</select>

Sometimes I want to render it as empty; I tried:

<select ... @if (!Model.IsEmpty) { <text>[email protected] asp-items=Model.Products</text> }>
</select>

That doesn't work.

I could repeat that markup in an if-else block, but hope there's a cleaner way to optionally invoke those tag helpers?


Solution

  • If you want to make dropdownlist optionally populate, change your code like below:

    <select asp-for="SelectedId" asp-items="@(Model.IsEmpty?null:Model.Products)"></select>
    

    Model design:

    public class YourViewModel
    {
        public int SelectedId { get; set; }
        public IEnumerable<SelectListItem> Products { get; set; }
        public bool IsEmpty { get; set; }
    }