如何在MVC中设置Html.DropDownListFor的默认值

时间:2014-12-04 15:06:10

标签: asp.net-mvc html-helper

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

 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 ,我想在其基础上设置类型,否则设置为红色。我尝试了很多,但对我没什么用。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分: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将设置默认值,视图上的选定值将以相同的值传回。

答案 1 :(得分:0)

这样做的错误方法

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)