23

我尝试搜索并没有找到任何可以解决我的问题的东西。我在 Razor 视图上有一个 DropDownList,它不会显示我在 SelectList 中标记为 Selected 的项目。这是填充列表的控制器代码:

var statuses  = new SelectList(db.OrderStatuses, "ID", "Name", order.Status.ID.ToString());
ViewBag.Statuses = statuses;
return View(vm);

这是查看代码:

<div class="display-label">
   Order Status</div>
<div class="editor-field">
   @Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
   @Html.ValidationMessageFor(model => model.StatusID)
</div>

我遍历它,即使在视图中它具有正确的 SelectedValue 但是 DDL 始终显示列表中的第一项,而不管所选值如何。谁能指出我做错了什么让 DDL 默认为 SelectValue?

4

7 回答 7

52

构造函数的最后一个参数SelectList(您希望能够在其中传递所选值 id)被忽略,因为 DropDownListFor 帮助器使用您作为第一个参数传递的 lambda 表达式并使用特定属性的值。

所以这是一个丑陋的方法:

模型:

public class MyModel
{
    public int StatusID { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // TODO: obviously this comes from your DB,
        // but I hate showing code on SO that people are
        // not able to compile and play with because it has 
        // gazzilion of external dependencies
        var statuses = new SelectList(
            new[] 
            {
                new { ID = 1, Name = "status 1" },
                new { ID = 2, Name = "status 2" },
                new { ID = 3, Name = "status 3" },
                new { ID = 4, Name = "status 4" },
            }, 
            "ID", 
            "Name"
        );
        ViewBag.Statuses = statuses;

        var model = new MyModel();
        model.StatusID = 3; // preselect the element with ID=3 in the list
        return View(model);
    }
}

看法:

@model MyModel
...    
@Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)

这是使用真实视图模型的正确方法:

模型

public class MyModel
{
    public int StatusID { get; set; }
    public IEnumerable<SelectListItem> Statuses { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // TODO: obviously this comes from your DB,
        // but I hate showing code on SO that people are
        // not able to compile and play with because it has 
        // gazzilion of external dependencies
        var statuses = new SelectList(
            new[] 
            {
                new { ID = 1, Name = "status 1" },
                new { ID = 2, Name = "status 2" },
                new { ID = 3, Name = "status 3" },
                new { ID = 4, Name = "status 4" },
            }, 
            "ID", 
            "Name"
        );
        var model = new MyModel();
        model.Statuses = statuses;
        model.StatusID = 3; // preselect the element with ID=3 in the list
        return View(model);
    }
}

看法:

@model MyModel
...    
@Html.DropDownListFor(model => model.StatusID, Model.Statuses)
于 2012-04-06T06:19:17.653 回答
3

为每个视图创建一个视图模型。这样做你只会在屏幕上包含需要的内容。由于我不知道您在哪里使用此代码,让我们假设您有一个创建视图来添加新订单。

为您的 Create 视图创建一个新的视图模型:

public class OrderCreateViewModel
{
     // Include other properties if needed, these are just for demo purposes

     // This is the unique identifier of your order status,
     // i.e. foreign key in your order table
     public int OrderStatusId { get; set; }
     // This is a list of all your order statuses populated from your order status table
     public IEnumerable<OrderStatus> OrderStatuses { get; set; }
}

订单状态类:

public class OrderStatus
{
     public int Id { get; set; }
     public string Name { get; set; }
}

在您的创建视图中,您将拥有以下内容:

@model MyProject.ViewModels.OrderCreateViewModel

@using (Html.BeginForm())
{
     <table>
          <tr>
               <td><b>Order Status:</b></td>
               <td>
                    @Html.DropDownListFor(x => x.OrderStatusId,
                         new SelectList(Model.OrderStatuses, "Id", "Name", Model.OrderStatusId),
                         "-- Select --"
                    )
                    @Html.ValidationMessageFor(x => x.OrderStatusId)
               </td>
          </tr>
     </table>

     <!-- Add other HTML controls if required and your submit button -->
}

您的 Create 操作方法:

public ActionResult Create()
{
     OrderCreateViewModel viewModel = new OrderCreateViewModel
     {
          // Here you do database call to populate your dropdown
          OrderStatuses = orderStatusService.GetAllOrderStatuses()
     };

     return View(viewModel);
}

[HttpPost]
public ActionResult Create(OrderCreateViewModel viewModel)
{
     // Check that viewModel is not null

     if (!ModelState.IsValid)
     {
          viewModel.OrderStatuses = orderStatusService.GetAllOrderStatuses();

          return View(viewModel);
     }

     // Mapping

     // Insert order into database

     // Return the view where you need to be
}

当您单击提交按钮时,这将保留您的选择,并被重定向回创建视图以进行错误处理。

我希望这有帮助。

于 2012-04-06T13:23:05.260 回答
3

当您在模型中声明它时,请确保您的返回选择值是 String 而不是 int。

例子:

public class MyModel
{
    public string StatusID { get; set; }
}
于 2017-11-02T17:13:12.857 回答
0

对我来说,这个问题是由大的 css 填充数字(下拉字段内的顶部和底部填充)引起的。基本上,该项目正在显示但不可见,因为它已经下降了。我通过使我的填充数字更小来修复它。

于 2018-10-06T01:58:13.637 回答
0

我留下这个以防它帮助别人。我有一个非常相似的问题,没有一个答案有帮助。

我的 ViewData 中有一个与 lambda 表达式的选择器同名的属性,基本上就好像你已经ViewData["StatusId"]设置了一些东西一样。

在我更改 ViewData 中匿名属性的名称后,DropDownList 助手按预期工作。

不过很奇怪。

于 2019-01-23T10:24:57.613 回答
0

我的解决方案是这样的......当前选定的项目是 ProjectManagerID。

看法:

@Html.DropDownList("ProjectManagerID", Model.DropDownListProjectManager, new { @class = "form-control" })

模型:

public class ClsDropDownCollection
{
   public List<SelectListItem> DropDownListProjectManager { get; set; }
   public Guid ProjectManagerID { get; set; }
}

生成下拉列表:

public List<SelectListItem> ProjectManagerDropdown()
{
    List<SelectListItem> dropDown = new List<SelectListItem>();
    SelectListItem listItem = new SelectListItem();

    List<ClsProjectManager> tempList = bc.GetAllProductManagers();           

    foreach (ClsProjectManager item in tempList)
    {
        listItem = new SelectListItem();
        listItem.Text = item.ProjectManagerName;
        listItem.Value = item.ProjectManagerID.ToString();
        dropDown.Add(listItem);
    }
    return dropDown;
}
于 2019-08-02T10:30:47.763 回答
-3

请在下面找到示例代码。

public class Temp
    {
        public int id { get; set; }
        public string valueString { get; set; }
    }

控制器

public ActionResult Index()
        {
            // Assuming here that you have written a method which will return the list of Temp objects.
            List<Temp> temps = GetList();

            var tempData = new SelectList(temps, "id", "valueString",3);
            ViewBag.Statuses = tempData;

            return View();
        }

看法

 @Html.DropDownListFor(model => model.id, (SelectList)ViewBag.Statuses)
    @Html.ValidationMessageFor(model => model.id)
于 2012-04-06T06:30:57.710 回答