在我看来,它不起作用......
@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);
}
答案 0 :(得分: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)