我有以下代码,可以生成包含值的下拉列表:
@Html.DropDownListFor(m => Model.BeslutsinformationstypId, VardemangderHelper.BeslutsInformationsTyperForInteckningarGetList(), new { @class = "form-control")})
现在我想要一个默认的选择选项。我尝试过以下方法:
@Html.DropDownListFor(m => Model.BeslutsinformationstypId, VardemangderHelper.BeslutsInformationsTyperForInteckningarGetList(), new { @class = "form-control", Selected = VardemangderHelper.BeslutsInformationsTyperForInteckningarGetList().First(x => x.Value == "320").Selected = true})
但这行不通。如何根据 VardemangderHelper.BeslutsiinformationsTyperForInteckningarGetList()
中的值设置所选选项?
可以在 Razor 中执行此操作吗?
最佳答案
如果您需要在呈现 View 时默认选择一个选项,则需要在返回 View 之前设置 Model.BeslutsinformationstypId
属性,如下所示:
var model = // My model instantiation
// He set some properties if you want
model.BeslutsinformationstypId = 320;
return View(model);
如果您可以在操作中设置它,则可以在 View 内执行它,但我更喜欢将其设置到 Controller 操作中:
@{
Model.BeslutsinformationstypId = 320
}
您的下拉列表仍将是您在问题中编写的同一行代码:
@Html.DropDownListFor(m => Model.BeslutsinformationstypId, VardemangderHelper.BeslutsInformationsTyperForInteckningarGetList(), new { @class = "form-control")})
关于c# - 在下拉列表 Razor 中设置所选选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43849128/