首页 > 解决方案 > 如何使用 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)

标签: asp.netmodel-view-controllerdropdown

解决方案


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.

DEMO


推荐阅读