MVC DropDownList SelectedValue无法正确显示

时间:2012-04-06 04:05:46

标签: asp.net-mvc asp.net-mvc-3 html.dropdownlistfor

我尝试搜索,但没有找到解决问题的方法。我在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吗?

7 个答案:

答案 0 :(得分:47)

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)

答案 1 :(得分:2)

为每个视图创建一个视图模型。这样做只会包含屏幕上所需的内容。由于我不知道您在何处使用此代码,因此我们假设您有一个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 -->
}

您的创建操作方法:

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
}

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

我希望这会有所帮助。

答案 2 :(得分:1)

确保在模型中声明返回的选择值是一个字符串,而不是和int。

示例:

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

答案 3 :(得分:0)

对我来说,问题是由较大的CSS填充数字(下拉字段内的顶部和底部填充)引起的。基本上,该项目处于显示状态,但由于状态太低而不可见。我通过缩小填充数来解决它。

答案 4 :(得分:0)

如果有其他帮助,我会保留。我遇到了一个非常类似的问题,但所有答案都没有帮助。

我在ViewData中有一个属性,与lambda表达式的选择器同名,基本上就像您将ViewData["StatusId"]设置为某项一样。

在ViewData中更改匿名属性的名称后,DropDownList帮助程序将按预期工作。

虽然很奇怪。

答案 5 :(得分:0)

我的解决方法是... 当前选择的项目是ProjectManagerID。

查看:

develop

型号:

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

生成下拉列表:

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

答案 6 :(得分:-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)