将默认值设置为选择列表

本文关键字:选择 列表 设置 默认值 | 更新日期: 2023-09-27 18:22:04

我有这个字符串列表:

public static readonly List<string> LIST_ITEM_STATE = new List<string>
{
    "Brand new",
    "Never used",
    "Slightly used",
    "Used",
    "Heavily used",
    "Damaged",
    "Ruined",
    "Run for your life"
};

我正在类中以这种方式构建一个选择列表:

public string mItemState { get; set; }
public IEnumerable<SelectListItem> mItemStateList { get; set; }
mItemStateList = new SelectList(ValueDomain.LIST_ITEM_STATE);

而且,在我看来,我将dropdownlistfor渲染成这样:

Item State: @Html.DropDownListFor(_item => _item.mItemState, Model.mItemStateList, String.Empty)

dropdownlist的工作方式很有魅力,但我一直在寻找方法,通过在Brand New处defaul设置所选值,同时保留String.Emtpty选项。我怎么能那样做?

将默认值设置为选择列表

我想你必须这样做:

public static readonly List<string> LIST_ITEM_STATE = new List<string>
{
    string.Empty,
    "Brand new",
    "Never used",
    "Slightly used",
    "Used",
    "Heavily used",
    "Damaged",
    "Ruined",
    "Run for your life"
};

并在SelectList:中设置所选值

 mItemStateList = new SelectList(ValueDomain.LIST_ITEM_STATE, "Brand new");

或者确保属性的值设置为您想要的初始值:

_item.mItemState = "Brand new";

这样定义SelectList:

mItemStateList = new SelectList(ValueDomain.LIST_ITEM_STATE, mItemState);