MVC 6 - TagHelper Select

血红的双手。 提交于 2019-12-11 00:05:16

问题


This may be a stupid question but I do not know why this is the default behavior for the Select TagHelper.

This is what I have in my view

<select asp-for="Estimators" asp-items="Model.Estimators" class="form-control"></select>

and this is the output on the page

<select class="form-control" id="Estimators" multiple="multiple" name="Estimators"><option value="2">Enio LastName</option>
<option value="6">Ianko Diaz</option>
<option value="7">Iordan Diaz</option>
<option value="8">Joan Alonso</option>
<option value="5">Lazaro Araya</option>
<option value="3">Leydis Martinez</option>
<option value="4">Ruben Cruz</option>
<option value="1">Shamir Ajate</option>
<option value="9">Yudiel Curbelo</option>
</select>

why is the select tag rendering as multiple="multiple".


回答1:


You are actually using the helper wrong. You should have another property to store the selected item.

public class YourViewModel
{
   public int SelectedEstimator { set; get; }
   public List<SelectListItem> Estimators { set; get; }
}

And in your view

@model YourViewModel
<select asp-for="SelectedEstimator" asp-items="@Model.Estimators">
    <option>Please select one</option>
</select>

This will render a single selectable SELECT element.

When the property you use for asp-for items is of array type, the generated select element will be multi select.

public class YourViewModel
{
   public int[] SelectedEstimator { set; get; }
   public List<SelectListItem> Estimators { set; get; }
}


来源:https://stackoverflow.com/questions/35110217/mvc-6-taghelper-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!