【问题标题】:Create DropDownListFor from SelectList with default value使用默认值从 SelectList 创建 DropDownListFor
【发布时间】:2013-06-20 13:57:04
【问题描述】:

我有一个dropdownlistfor

 @Html.DropDownListFor(model => model.Item.Item.Status, new SelectList(@Model.AllStatus, "id", "Description"), new { id = "statusDropdown" })
 @Html.ValidationMessageFor(model => model.Item.Item.Status)

HTML 输出:

<select id="statusDropdown" class="valid" name="Item.Item.Status" data-val-required="The Status field is required." data-val-number="The field Status must be a number." data-val="true">
<option value="2">Completed by Admin</option>
<option value="3">General Error</option>
<option value="4">New</option>
</select>

如何更新此代码以设置默认选定选项?例如

&lt;option value="4" selected&gt;New&lt;/option&gt;

我试过了:

 @Html.DropDownListFor(model => model.Item.Item.Status, new SelectList(@Model.AllStatus, "id", "Description",@Model.SelectedStatusIndex), new { id = "statusDropdown" })

@Model.SelectedStatusIndex 的值为 4,但不会将默认选项更改为 New。

我也试过了:

@Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.AllStatus, "id", "Description"), new { id = "statusDropdown" })
@Html.ValidationMessageFor(model => model.Item.Item.Status)

这会选择默认选项“新建”,但 HTTP POST 上的下拉菜单未设置 model.Item.Item.Status

其他详情:

model.Item.Item.Status 是一个整数。 @Model.AllStatus 是一个列出所有可用状态选项的 SQL 表。

【问题讨论】:

    标签: c# asp.net-mvc-4


    【解决方案1】:

    关于 herethere 的讨论已经存在。其中一个问题可能是使用与string 不同的类型作为键值。我过去遇到过类似的问题,我知道我解决了它,就像this - 在准备列表时明确设置Selected 属性(在你的情况下,AlLStatus)。

    这意味着,对于您的情况(在控制器操作中):

    IEnumerable<SelectListItem> selectList = 
    from s in allStatus // where ever you get this from, database etc.
    select new SelectListItem
    {
        Selected = (s.id == model.Item.Item.Status),
        Text = cs.Description,
        Value = s.id.ToString()
    };
    model.AllStatus = selectList;
    

    【讨论】:

      【解决方案2】:

      这是对上述答案的补充。这就是我应该做的。

      视图模型用于表示您的数据。因此,对于单个下拉列表,我将拥有以下内容:

      public class MyViewModel
      {
           public int StatusId { get; set; }
      
           public IEnumerable<Status> Statuses { get; set; }
      }
      

      Status 类看起来像这样:

      public class Status
      {
           public int Id { get; set; }
      
           public string Description { get; set; }
      }
      

      控制器处理视图的action方法:

      public class MyController
      {
           private readonly IStatusService statusService;
      
           public MyController(IStatusService statusService)
           {
                this.statusService = statusService;
           }
      
           public ActionResult MyActionMethod()
           {
                MyViewModel viewModel = new MyViewModel
                {
                     Statuses = statusService.GetAll(),
                     StatusId = 4 // Set the default value
                };
      
                return View(viewModel);
           }
      }
      

      视图将如下所示:

      @model MyProject.ViewModels.MyViewModel
      
      @Html.DropDownListFor(
           x => x.StatusId,
           new SelectList(Model.Statuses, "Id", "Description", Model.StatusId),
           "-- Select --"
      )
      @Html.ValidationMessageFor(x => x.StatusId)
      

      你去。

      【讨论】:

        【解决方案3】:

        我最终使用了 thomasjaworski 答案的变体。

        查看:

        @Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), new { id = "statusDropdown" })
        

        ViewModel 构造函数

                StatusSelectList = AllStatus.Select(x =>
                                                new StatusSelectListItem
                                                {
                                                    Text = x.Description,
                                                    Value = x.id.ToString()
                                                }).ToList();
        
                this.SelectedStatusIndex = 2;//Default Status is New
        

        HTTP POST 控制器

        我将model.Item.Item.Status 与下拉列表本身分开设置:

        model.Item.Item.Status = model.SelectedStatusIndex;
        

        因为下拉集是作为第一个参数传递的表达式的值:

        @Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), new { id = "statusDropdown" })
        

        在这种情况下,model.SelectedStatusIndex 是由下拉菜单设置的。我发现这个控制器实现很棘手。

        【讨论】:

        • 感谢您发布您的解决方案!
        • P.S.如果您使用 @Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text")) 选择列表的 id 将是 SelectedStatusIndex.... 另外如果您使用 @ Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), "Please Select") 它将把 Please Select 作为第一个条目。
        • 是的,但是如何将“请选择”指定为 -1 的值?
        【解决方案4】:

        您可以使用“插入”添加下拉菜单的默认值并将其添加到您的动态列表中: 通过这种方式,您不需要在视图中使用 Razor。

        List<Y> m = X.GetList();
        m.Insert(0, new Y{ Name = "--Select--" });
        

        【讨论】:

          【解决方案5】:
          SelectList ProductSizeList = new SelectList(_context.Sizes, "SizeId", "SizeName");
          
          //after you create the selectList you have to create the default select list item            
          SelectListItem AllSize = new SelectListItem("All Size", "0");
          
          // and after this you add this item to the begin of the selectlist
          ViewData["SizeId"] = ProductSizeList.Prepend(AllSize);
          

          【讨论】:

            【解决方案6】:

            我为 DropDownListFor 的表达式分配了已经在 List 中定义的值。这个对我有用。我使用List&lt;SelectListItem&gt; Model.IncidentPriorityList 作为 ddwn 的选择列表。

            Model.incident.INCIDENT_PRIORITY_ID = Model.DefaultParameterId;
            @Html.DropDownListFor(m => m.incident.INCIDENT_PRIORITY_ID, Model.IncidentPriorityList, "Select", new { @class= "form-control selectpicker", id = "drpPriority", @required = true })

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2014-06-29
              • 1970-01-01
              • 1970-01-01
              • 2020-06-19
              • 2012-06-27
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多