如何在CSHTML可编辑下拉框中默认选中PT2而非Select?
解决默认选中“PT2”的方案
现有代码的问题
你当前同时使用了HTML5的<input list>和DropDownListFor,这会生成两个独立的表单控件,不仅功能冲突,也无法实现默认选中“PT2”的需求;且DropDownListFor的SelectList写法未正确配置选中逻辑。
两种可行实现思路
思路一:使用DropDownListFor实现(推荐,符合MVC模型绑定)
要让DropDownListFor默认选中“PT2”,有两种方式:
通过模型赋值(最规范)
在控制器初始化模型时,直接给ProductType属性赋值为“PT2”:public ActionResult YourAction() { var model = new Product { ProductTypeList = new List<string> { "PT1", "PT2", "PT3" }, ProductType = "PT2" // 设置默认选中值 }; return View(model); }页面上修正
DropDownListFor的写法(移除多余的<input>):@Html.DropDownListFor( model => model.ProductType, new SelectList(Model.ProductTypeList), // List<string>可直接作为数据源,Value和Text均为字符串本身 "Select", // 可选:保留占位提示文本,仅当ProductType为空时显示 new { @class = "form-control" } // 可选:添加样式类 )此时模型的
ProductType值会自动绑定为选中项,页面加载时默认选中“PT2”。直接在
SelectList中指定选中值
若不想在控制器赋值,可在SelectList构造函数中传入selectedValue参数:@Html.DropDownListFor( model => model.ProductType, new SelectList(Model.ProductTypeList, "PT2"), // 第三个参数为选中值 "Select", new { @class = "form-control" } )
思路二:使用HTML5 <datalist>实现(可编辑下拉)
如果你需要可编辑的下拉效果(用户可输入自定义内容,也可选择预设选项),则保留<input list>,移除DropDownListFor,手动生成datalist:
<input id="ProductType" list="ProductTypeList" name="product-type-list" value="PT2"> <datalist id="ProductTypeList"> @foreach (var type in Model.ProductTypeList) { <option value="@type">@type</option> } </datalist>
通过给<input>设置value="PT2",页面加载时会默认显示并选中“PT2”。
内容的提问来源于stack exchange,提问作者Mitu
相关产品推荐
相关产品推荐

