【问题标题】:Set selected option in dropdownlist razor在下拉列表剃刀中设置选定的选项
【发布时间】:2017-10-06 13:02:41
【问题描述】:

我有以下代码生成带有值的下拉列表:

@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 中执行此操作?

【问题讨论】:

标签: c# asp.net-mvc razor


【解决方案1】:

如果您需要在呈现视图时默认选择一个选项,那么您需要在返回视图之前设置Model.BeslutsinformationstypId 属性,如下所示:

var model = // My model instantiation
// He set some properties if you want
model.BeslutsinformationstypId = 320;

return View(model);

如果你可以在你的动作中设置它,你可以在视图中进行,但我更喜欢将它设置为控制器动作:

@{
     Model.BeslutsinformationstypId = 320
}

您的下拉菜单仍将是您在问题中编写的同一行代码:

@Html.DropDownListFor(m => Model.BeslutsinformationstypId, VardemangderHelper.BeslutsInformationsTyperForInteckningarGetList(), new { @class = "form-control")})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多