c# - 在下拉列表 Razor 中设置所选选项

标签 c# asp.net-mvc razor

我有以下代码,可以生成包含值的下拉列表:

@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/

相关文章:

c# - 将值从代码隐藏传递到 JavaScript 函数

c# - 从谷歌翻译方括号中拆分字符串

c# - 在没有 Visual Studio 的情况下添加引用

c# - 找不到 MVC 3 Html.BeginForm 表达式重载

c# - 从模式中的部分获取数据元素,用Javascript设置父级中文本框的值?

c# - 如何在 Linq 中编写 SQL Concat?

javascript - 从 JSON 数组访问字符串值

c# - 另一个项目中的 RedirectToAction

javascript - 选择列表中的 HTML 复选框

c# - 单选按钮始终选中的项目显示 False