0

在我看来,它不工作......

@model PASKAN.Web.Security.Models.User
<p class="lan-name"><label>Language</label>@Html.DropDownListFor(o => o.Language, Enum.GetValues(typeof(Enum)).Cast<Enum>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))</p>

我的语言模型如下

public enum Language {
    English = 0,
    Spanish=1,
    Latin =3
}

我的控制器看起来像这样

public ActionResult Edit()
{
    Models.User user = new User(Convert.ToInt32(User.Identity.Name));
    ViewBag.Languages = Enum.GetNames(typeof(Language)).ToList();
    return View (user);
}
4

1 回答 1

2

您在 ViewBag 中填充了语言,因此在您的视图中使用它们:

@Html.DropDownListFor(o => o.Language, (IEnumerable<SelectListItem>)ViewBag.Languages)

但请确保您使用了助手期望的正确类型:

public ActionResult Edit()
{
    Models.User user = new User(Convert.ToInt32(User.Identity.Name));
    ViewBag.Languages = Enum
        .GetNames(typeof(Language))
        .Select(x => new SelectListItem { Value = x, Text = x })
        .ToList();
    return View (user);
}

但是由于您提到了有关视图模型的内容,因此我认为您误用了该术语。在您的情况下,我看不到任何视图模型的痕迹。视图模型看起来像这样:

public class MyViewModel
{
    public string Language { get; set; }
    public IEnumerable<SelectListItem> Languages { get; set; }
}

您的控制器操作将传递给视图:

public ActionResult Edit()
{
    var user = new User(Convert.ToInt32(User.Identity.Name));
    var viewModel = new MyViewModel
    {
        Language = user.Language,
        Languages = Enum
            .GetNames(typeof(Language))
            .Select(x => new SelectListItem { Value = x, Text = x })
            .ToList()
    };
    return View (viewModel);
}

在您的强类型视图中:

@model MyViewModel
...
@Html.DropDownListFor(x => x.Language, Model.Languages)
于 2013-06-20T10:27:04.337 回答