0

我怎样才能使这项工作

@using (Html.BeginForm())
{
@Html.ValidationSummary()
    <p>MYep @Html.DropDownListFor(x => x.Id, new int {
                          new SelectListItem() {Text = "asdad", Value = "1"},
                          new SelectListItem() {Text = "dfgdgd", Value = "2"},
                          new SelectListItem() {Text = "werwrwt", Value = "3"}, "Choose")

<input type="submit" value="Ok" />

}

或者我应该在之前制作一个 IEnumerable 列表并将其提供给 dropdownlistfor?

4

2 回答 2

2

Matt's answer is fine, but it looks like you are using a ViewModel, so you should just put this static list into the view model and reference the list in your View.

ViewModel:

public sealed class MyViewModel
{
    public int Id { get; set; }
    public List<SelectListItem> IdList
    {
        get
        {
            return new List<SelectListItem> 
            { 
                new SelectListItem { Text = "asdad", Value = "1" }, 
                new SelectListItem { Text = "dfgdgd", Value = "2" }, 
                new SelectListItem { Text = "werwrwt", Value = "3" } 
            };
        }
    }
}

View:

@Html.DropDownListFor(x => x.Id, Model.IdList)
于 2013-07-23T00:56:39.980 回答
1

您正在声明一个类型的对象int并使用 s 的列表填充它SelectListItem,这将不起作用。

我认为您想要这样的东西...如果 x.Id 是 int 并且所有下拉值都是字符串,您可能需要进行一些修改,但我不确定。

@Html.DropDownListFor(x => x.Id, new List<SelectListItem> {                          
      new SelectListItem() {Text = "asdad", Value = "1"},
      new SelectListItem() {Text = "dfgdgd", Value = "2"},
      new SelectListItem() {Text = "werwrwt", Value = "3"}}, "Choose")
于 2013-07-22T23:32:25.063 回答