【问题标题】:How to set the default value for Html.DropDownListFor in MVC如何在 MVC 中为 Html.DropDownListFor 设置默认值
【发布时间】:2014-12-04 15:06:10
【问题描述】:

我有以下代码: 控制器方法

 public ActionResult Register(int? registrationTypeId)
        {
            IEnumerable<AccountType> accountTypes = new List<AccountType>
            {
                new AccountType
                {
                    AccountTypeId = 1,
                    AccountTypeName = "Red"
                },
                new AccountType
                {
                    AccountTypeId = 2,
                    AccountTypeName = "Blue"
                }
            };
           // I want to select account type on registrationTypeId
            ViewBag.AccountTypes = accountTypes;
            return View();
      }

查看

<div class="col-md-10">
            @Html.DropDownListFor(n => n.AccountType,
         new SelectList(ViewBag.AccountTypes, "AccountTypeId", "AccountTypeName"), new { @class = "form-control" })
</div>

型号

public class RegisterViewModel
    { 
        [Required]
        [Display(Name = "Account Type")]
        public int AccountType { get; set; 
    }

正如您在控制器中看到的 registrationTypeId ,如果它不是 null ,我想在其基础上设置类型,否则设置为红色。我已经尝试了很多,但对我没有任何帮助。任何帮助将不胜感激!

【问题讨论】:

标签: asp.net-mvc html-helper


【解决方案1】:

我强烈建议您不要通过查看包传递您的列表。已经看到了太多导致重大问题的问题。将此添加到您的模型中

public List<SelectListItem> AccountTypes { get; set; }

在您的控制器中的 get 方法中设置您的默认值并设置您的列表

Model.AccountType = 1;  // change the one to your default value
Model.AccountTypes = accountTypes;  //instead of ViewBag.AccountTypes = accountTypes;

那么在你看来

@Html.DropDownListFor(x => x.AccountType, Model.AccountTypes)

在将模型传递给视图之前设置 AccountType 将设置默认值,并且视图上的选定值将以相同的值传回。

【讨论】:

  • 为什么在示例和开箱即用项目中的 ViewBag 中将列表传递给视图?
  • 我猜这是让它工作的一种快速而肮脏的方式。通过模型传递列表更加稳定和可靠。
  • Microsoft 的示例以不是非常经得起行业考验而闻名,并且不幸的是经常显示“最糟糕的做法”......因为他们试图推销“易于编码”的想法,所以他们希望它在他们的网站上看起来尽可能简单
【解决方案2】:

这样做的错误方法

var accountTypes = new SelectList(accountTypes, "AccountTypeId", "AccountTypeName");

foreach(var item in accountList)
    if (item.AccountTypeId == registrationTypeId)
        item.Selected = true;

ViewBag.AccountTypes = accountTypes;

在视图中,

@Html.DropDownListFor(n => n.AccountType, (SelectList)ViewBag.AccountTypes)

【讨论】:

  • 您不应该(也不应该)这样做。设置item.Selected 属性会被@Html.DropDownListFor() 忽略,因此毫无意义。如果AccountType 的值与其中一个选项的值匹配,则该选项将被选中。
  • 没想到,以前从来没有这样做过。
  • 我就不说了,你的解释可能对人们有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
  • 2021-02-10
  • 2011-03-30
  • 1970-01-01
  • 2019-12-15
相关资源
最近更新 更多