asp.net - 如何使用 asp.net MVC 为 DropDownListFor 中的每个条目添加一个字符串?
问题描述
我正在做一个关于任务管理的项目。我创建了一个页面来创建一个新任务,并且我正在尝试添加一个包含财务期间的下拉列表(例如“2018-2019”、“2021-2022”)。
到目前为止,我尝试的是用简单的年份(从 2018 年到 2050 年)创建 SelectList,我在主视图中添加了正确的格式,但我不能在我的 DropDownListFor 中使用相同的东西。这是我现在拥有的:
模型 :
// List with years from 2018 to 2050
public IEnumerable<SelectListItem> TaskPeriods =
new SelectList(Enumerable.Range(2018, (2050 - 2018) + 1));
// Selected period
public int TaskPeriod { get; set; }
主视图(以正确格式输出):
@foreach(var items in Model)
{
<tr>
<td>@items.TaskPeriod-@(items.TaskPeriod + 1)</td>
</tr>
创建视图(下拉仅输出年份列表,我希望它以与主视图相同的格式显示年份)
@using (Html.BeginForm("NewTask", "Task", FormMethod.Post))
{
<div class="form-group">
<label>Financial Period</label><br/>
@Html.DropDownListFor(model => Model.TaskPeriod, new SelectList(Model.TaskPeriods, "Value", "Text"))
</div>
}
Output on main view has the "year - year+1" format which is correct but I couldn't find a way to display the same result in my dropdown (only shows "year" format)
解决方案
You need to format the Text string before binding with DropDownListFor
@{
var newSource = Model.TaskPeriods.Select(m => new SelectListItem
{
Value = m.Text.ToString(),
Text = string.Format("{0}-{1}", m.Text.ToString(),Convert.ToInt32(m.Text)+1)
});
SelectList finalSource = new SelectList(newSource, "Value ", "Text");
}
<div class="form-group">
<label>Financial Period</label><br/>
@Html.DropDownListFor(model => Model.TaskPeriods, finalSource)
</div>
In this case, your value is an original value (2018
) but the text looks like 2018-2019
if you want to change the value then modify the value parameter similarly.
推荐阅读
- firebase - Flutter & Firebase:注册用户如何为子用户创建账户
- java - 获取 LUUID,前提是我有一个 JUUID,来自 MongoDB for Kotlin with Spring Boot
- python - 尝试显示头部时出现数据框错误
- flutter - 颤振谷歌地图图像标记不会出现在中心
- flutter - 我们如何创建自定义的 getter 和 setter,在 Flutter 中这样做有什么好处?
- matlab - 使用 cplex 和 yalmip 的简单二进制矩阵不可行
- multithreading - 无法使用 bitbake 将 C 文件添加到 Yocto 层
- javascript - 使用 usestate 布尔值的反应性页面在 Reactnative 中不起作用
- bash - Bash glob,如何对非单位长度的字符串进行或运算?
- android - 升级flutter android构建工具