在mvc4的下拉列表中显示默认值

时间:2016-06-24 07:03:03

标签: c# asp.net-mvc-4 razor

在MVC4剃刀应用程序@ Html.DropDownList中使用ViewBag提供选择列表 但是如何将默认值设置为该下拉列表并没有得到。

 @Html.DropDownListFor(m => m.SlpCode, new SelectList(ViewBag.SalesEmployee1, "Value", "Description"), new { @class = "form-control" })

为此我尝试了

@Html.DropDownListFor(m => m.SlpCode, new SelectList(ViewBag.SalesEmployee1, "Value", "Description", (Model.SlpCode==-1)), new { @class = "form-control" }) 

但它仍然无法正常工作。 那是另一种解决方案?

1 个答案:

答案 0 :(得分:1)

这就是我正在为下拉列表做的事情

控制器代码

        public ActionResult Contact()
    {
        Contact homeViewModel = new Contact();
        homeViewModel.subject = new List<Subject>();
        homeViewModel.subject.Add(new Subject { Id = 1, subject1 = "General Customer Service" });
        homeViewModel.subject.Add(new Subject { Id = 2, subject1 = "Suggestions" });
        homeViewModel.subject.Add(new Subject { Id = 3, subject1 = "Product Support" });

        homeViewModel.Selectedid = 1; //this sets the default value for your dropdown

        return View(homeViewModel);
    }

型号代码:

public class Contact
 {   [Required(ErrorMessage="Please fill the following")]
    public string name { get; set; }

    [Required(ErrorMessage = "Please Enter Correct Username")]
    [RegularExpression(@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$", ErrorMessage = "Please provide valid email id")]
    public string email { get; set; }
    public List<Subject> subject { get; set; }
    [Required(ErrorMessage="Please fill the following")]
    public string message { get; set; }
    public int Selectedid { get; set; }
}

查看代码:

@Html.DropDownList("Selectedid", new SelectList(Model.subject, "Id",    "subject1", Model.Selectedid), new { @class = "form-control", id = "subject", required = "required" })