在模型中硬编码SelectList是通过在模型中定义一个SelectList属性,并在控制器中为该属性赋值。下面是一个示例:
public class YourModel
{
public SelectList YourSelectList { get; set; }
// 其他属性...
}
public IActionResult YourAction()
{
YourModel model = new YourModel();
// 构造SelectList对象并为YourSelectList属性赋值
model.YourSelectList = new SelectList(new[]
{
new { Value = "1", Text = "选项1" },
new { Value = "2", Text = "选项2" },
new { Value = "3", Text = "选项3" }
}, "Value", "Text", "2"); // 最后一个参数为默认选中项的值
return View(model);
}
public IActionResult YourAction()
{
YourModel model = new YourModel();
// 使用SelectList静态方法创建SelectList对象并为YourSelectList属性赋值
model.YourSelectList = SelectListHelper.CreateYourSelectList("2"); // 调用静态方法,传入参数
return View(model);
}
@model YourModel
@Html.DropDownListFor(m => m.PropertyName, Model.YourSelectList, "请选择")
@model YourModel
<select id="PropertyName" name="PropertyName">
@foreach (var item in Model.YourSelectList)
{
<option value="@item.Value" @(item.Value == Model.PropertyName ? "selected" : "")>@item.Text</option>
}
</select>
在上述代码中,你需要替换YourModel、YourSelectList、PropertyName和选项值、文本等名称来适应你的实际场景。
这样,你就在模型中硬编码了一个SelectList,并且可以在视图中使用该SelectList来呈现下拉列表。
领取专属 10元无门槛券
手把手带您无忧上云