如何设置的默认值Html.DropDownListFor在MVC [英] How to set the default value for Html.DropDownListFor in MVC

查看:568
本文介绍了如何设置的默认值Html.DropDownListFor在MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code:
控制器方法

 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 的控制器,我想设置的类型上的基地,如果它不是的无效,否则设置为红色。我已经尝试了很多,但没有为我工作。任何帮助将AP preciated!

As you can see registrationTypeId in controller , i want to set the type on its bases if it is not null ,otherwise set to red. I have tried a alot but nothing worked for me. Any help will be appreciated !

推荐答案

我会强烈建议您不要通过视图包通过你的列表中。见过太多的地方,才造成了重大问题的问题。添加到您的模型

I would highly recommend that you don't pass your list through the view bag. have seen too many questions where that has caused major issues. add this to your model

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

在您get方法控制器设置默认和设置您的列表

in your controller in the get method set your default and set your list

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模型传递给视图将设置默认前,在视图中选定值将被传递回相同的值。

setting AccountType before passing the model to the view will set the default and the selected value on the view will be passed back in that same value.

这篇关于如何设置的默认值Html.DropDownListFor在MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆