How to remove multiple attribute in tag helper ASP.NET MVC

554 Views Asked by At

In my code behind:

var lstGroupProduct = await _db.GroupProduct.Select(x => new SelectListItem
        {
            Text = x.Name,
            Value = x.GroupProductId.ToString()
        }).ToListAsync();

And my code tag helper:

<select asp-for="ListGroupProduct" name="groupProductId" id="groupProductId" asp-items="@Model.ListGroupProduct">
</select>

But when code render to HTML will:

<select name="groupProductId" id="groupProductId" multiple="multiple">
    <option value="1">Normal</option>
    <option value="2">Hard</option>
    <option value="3">Skin care, pill</option>
</select>

When code renders the HTML, I expectit NOT to include multiple attributes. I tried to remove by jQuery but seem this not best selection.

1

There are 1 best solutions below

0
On

asp-for attribute will result in the multiple attribute being rendered.

<select asp-for="ListGroupProduct" name="groupProductId" id="groupProductId" asp-items="@Model.ListGroupProduct">
</select>

This will render the HTML markup for the select element with the multiple attribute which will allow the user to select multiple options.

Use name attribute to bind: it will not generate multiple attribute .

<select name="ListGroupProduct" name="groupProductId" id="groupProductId" asp-items="@Model.ListGroupProduct">
</select>

Output:

<select name="groupProductId" id="groupProductId">
    <option value="1">Normal</option>
    <option value="2">Hard</option>
    <option value="3">Skin care, pill</option>
</select>

https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-6.0