首页 文章

MVC DropDownList SelectedValue无法正确显示

提问于
浏览
20

我试过搜索,没有发现任何解决我问题的方法 . 我在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吗?

6 回答

  • 0

    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)
    
  • -3

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

    为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

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

    例:

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

    对我来说,问题是由大的css填充数字(下拉字段内的顶部和底部填充)引起的 . 基本上,该项目正在显示但不可见,因为它是向下的 . 我通过使填充数字更小来固定它 .

  • 0

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

    我的ViewData中有一个属性,其名称与lambda表达式的选择器相同,基本上就像你将 ViewData["StatusId"] 设置为某个东西一样 .

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

    虽然奇怪 .

  • 1

    请在下面找到示例代码 .

    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)
    

相关问题