c#-在MVC3的下拉列表中设置所选项目

我必须为视图中的下拉列表设置选定的项目.但是它不起作用.

//视图

<div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
           @Html.DropDownListFor(model => model.Gender,Model.GenderList)
        </div>

//模型

[Required(ErrorMessage = "Please select gender!")]
        [Display(Name = "Gender")]
        public string Gender { get; set; }

  public IEnumerable<SelectListItem> GenderList
        {
            get
            {
                return new[]
            {
                new SelectListItem { Value = "0", Text = "Select" },
                new SelectListItem { Value = "1", Text = "Male" },
                new SelectListItem { Value = "2", Text = "Female" },
            };
            }
        }

性别属性具有需要在列表中选择的值.还是行不通.

我哪里错了?

解决方法:

首先,创建您的ViewModel.

public class MovieViewModel
{
    public string Genre { get; set; }

    public IEnumerable<SelectListItem> GenreList
    {
        get
        {
            yield return new SelectListItem { Text = "Comedy", Value = "1" };
            yield return new SelectListItem { Text = "Drama", Value = "2" };
            yield return new SelectListItem { Text = "Documentary", Value = "3" };
        }
    }
}

然后,您的控制器创建此ViewModel的新实例,并将其发送到视图.

public class HomeController : Controller
{
    //
    // GET: /Home/
    public ActionResult Index()
    {
        var viewModel = new MovieViewModel
        {
            Genre = "2"
        };

        return View(viewModel);
    }
}

最后,该视图使用ASP.NET包装器[Html.DropDownListFor()] [1]显示下拉列表.

@model MvcApplication1.Models.MovieViewModel

<!DOCTYPE html>

<html>
<head>
    <title>My movie</title>
</head>
<body>
    <div>
        @Html.DropDownListFor(m => m.Genre, Model.GenreList)
    </div>
</body>
</html>

然后根据ViewModel自动选择选定的值.无需手动设置对象SelectListitem的Selected属性.

上一篇:C#-ASP.Net MVC表单发布无法绑定模型列表属性


下一篇:c#-从列表中的简单下拉列表