2014-12-04 56 views
0

我有以下代码: 控制器方法如何在MVC设定的默认值Html.DropDownListFor

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,否则设置为红色。我尝试了很多,但没有为我工作。任何帮助将不胜感激 !

+0

你的模型是什么样的? – CodeCaster 2014-12-04 15:08:40

+0

[我怎样才能让这个ASP.NET MVC SelectList工作?](http://stackoverflow.com/questions/781987/how-can-i-get-this-asp-net-mvc-selectlist-工作) – CodeCaster 2014-12-04 15:09:13

+0

设置AccountType设置默认 – 2014-12-04 15:09:33

回答

1

我会强烈建议您不要通过视图包通过你的列表。在那些导致重大问题的地方看到了太多的问题。这在你的控制器get方法传递模型前添加到模型

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

设置默认和设置您的列表

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到视图将设置默认值,视图上的选定值将以相同的值传回。

+0

为什么列表在示例和现成盒项目中传递给ViewBag中的视图? – 2014-12-05 09:45:22

+0

我的猜测是它是一种快速和肮脏的方式来使其工作。通过模型传递清单要稳定可靠得多。 – 2014-12-05 16:47:03

+0

微软的例子很出名,因为它不是非常符合行业的证据,并且不幸的是经常显示“最糟糕的做法”......因为他们试图推销“易于编码”的想法,所以他们希望它尽可能简单网站 – nothingisnecessary 2017-03-01 19:39:23

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) 
+0

你不(也不应该)这样做。设置'item.Selected'属性被'@ Html.DropDownListFor()'忽略,所以它没有意义。如果'AccountType'的值与其中一个选项的值匹配,那么该选项将被选中。 – 2014-12-04 23:11:18

+0

没有意识到,从来没有像这样做过。 – 2014-12-05 09:43:29

+0

我会放弃它,你的解释可能会帮助人们。 – 2014-12-05 09:50:27