在MVC3中创建一个简单的下拉列表

时间:2012-07-06 11:32:01

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

我有一个文本框,用于记录工作角色的值。但是,这限制了数据库方面的一定数量的角色。因此,使用仅包含有效角色的下拉列表对我来说更有意义。我试图解决这个问题,但遇到了困难。

我在我的视图中放置了以下代码:

<p>
    @Html.LabelFor(m => m.Role)
    @Html.DropDownListFor(m=>m.Roles)
    @Html.ValidationMessageFor(m => m.Role)
</p>

这在我的模型中:

public List<string> Roles
    {
        get
        {
            return new {"Author","Underwriter" };
        }
    }

但这不会编译。我有什么想法吗?

2 个答案:

答案 0 :(得分:6)

您需要在视图模型上使用2个属性才能创建下拉列表:标量属性将保存所选值,而集合属性包含您要显示的可用项列表。

因此,您一如既往地编写视图模型:

public class MyViewModel
{
    [Required]
    [DisplayName("Role")]
    public string SelectedRole { get; set; }

    public IEnumerable<SelectListItem> Roles 
    {
        get
        {
            return new[]
            {
                new SelectListItem { Value = "Author", Text = "Author" },
                new SelectListItem { Value = "Underwriter", Text = "Underwriter" }
            };
        }
    }
}

然后是一个控制器动作,将该模型传递给视图:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        return Content("Thanks for selecting role: " + model.SelectedRole);
    }
}

最后是一个相应的强类型视图:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.SelectedRole)
    @Html.DropDownListFor( m => m.SelectedRole, Model.Roles, "-- Role --")
    @Html.ValidationMessageFor(m => m.SelectedRole)

    <button type="submit">OK</button>
}

答案 1 :(得分:0)

List<string>添加到创建声明

public List<string> Roles
    {
        get
        {
            return new List<string> {"Author","Underwriter" };
        }
    }
相关问题