如何将语法从@Html.RadioButtonFor 迁移到@Html.DropdownlistFor?

How to migrate the syntax from @Html.RadioButtonFor to @Html.DropdownlistFor?

如何将语法从@Html.RadioButtonFor迁移到@Html.DropdownlistFor?

我必须将一些具有单选按钮列表的语法迁移到下拉列表中。这是由于页面屏幕间距问题。

将语法从 RadioButtonFor 更改为 DropdownlistFor 没有帮助。

 <div class="col-sm-1">


                            @foreach (var item in Model.LevelList)
                            {
                                @Html.RadioButtonFor(model => model.TimesPerDay, item.ID, new { @id = "TimesPerDay" + item.ChoiceText }) @:  @item.ChoiceText
                            }

                            <span asp-validation-for="TimesPerDay" class="text-danger"></span>
                        </div>

这应该有效:

<div class="col-sm-1">
        @Html.DropDownListFor(m => m.TimesPerDay, Model.ExerciseLevelList.Select(e => new SelectListItem() { Text = e.ChoiceText, Value = e.ID.ToString() }))
        <span asp-validation-for="TimesPerDay" class="text-danger"></span>
</div>

参见参考文献:SelectExtensions.DropDownListFor

我不确定您是否能够轻松地为每个下拉列表项单独应用 html 属性(但您可以通过方法重载简单地为整个下拉列表执行此操作)

您可以创建一个类型为 List<SelectListItem> 的视图模型 属性 并将其作为 DropDownListFor 选项列表(或 <select> 标签助手,具体取决于您的选择):

型号

public class ViewModel
{
    // other properties

    public List<SelectListItem> ExerciseLevelSelectList { get; set; }
}

控制器

public IActionResult ActionName()
{
    var model = new ViewModel();

    // data processing logic here

    model.ExerciseLevelSelectList = model.ExerciseLevelList.Select(x => new SelectListItem
    {
        Text = x.ChoiceText,
        Value = x.ID.ToString() // string conversion if ID has numeric value
    });

    return View(model);
}

查看

使用 HTML 助手:

@Html.DropDownListFor(m => m.TimesPerDay, Model.ExerciseLevelSelectList, ...)

使用select tag helper:

<select asp-for="TimesPerDay" asp-items="Model.ExerciseLevelSelectList"></select> 

请注意 SelectListItem 实例的 Value 属性 具有 string 类型(检查 here),因此 ToString() 是必需的,如果你想要将数值传递给 属性.

你可以试试这个

<div class="col-sm-1">
<%:Html.DropDownListFor(model => model.NewMode, new SelectList(Model.PaymentModeList, "PaymentModeDescription", "PaymentModeDescription"), "Select Mode", new { @class = "inputtext width200px" })%>                    

</div>