如何在ASP.NET MVC3中创建下拉列表?

时间:2012-03-25 15:52:14

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

我正在尝试根据链接到模型的允许值列表在ASP.NET MVC3视图中创建一个下拉列表。

到目前为止,在我的模型中,我得到了:

namespace NS 
{
    public class Model
    {
        public Model() 
        {
            Status = new List<SelectListItem>();
            Status.Add(new SelectListItem { Text = "New", Value = "New" });
            Status.Add(new SelectListItem { Text = "PaymentPending", Value = "PaymentPending" });
            Status.Add(new SelectListItem { Text = "PaymentProcessed", Value = "PaymentProcessed" });
            Status.Add(new SelectListItem { Text = "Dispatched", Value = "Dispatched" });
            Status.Add(new SelectListItem { Text = "Complete", Value = "Complete" });
            Status.Add(new SelectListItem { Text = "Cancelled", Value = "Cancelled" });
        }

        public List<SelectListItem> Status { get; set; }
    } // class Model
} // NS

(显然需要修剪不必要的东西)

然后在我看来我得到了:

@model NS.Model
@Html.DropDownListFor(Model.Status)

正如在SO上寻找答案似乎暗示的那样。但是我收到了一个错误:

  

编译器错误消息:CS1501:方法'DropDownListFor'没有重载需要1个参数

任何提示都非常赞赏。

2 个答案:

答案 0 :(得分:5)

错误信息非常明显,DropDownListFor helper有两个参数。

修改模型以使属性包含所选值

public class Model
{
public Model() {
  Status = new List<SelectListItem>();
  Status.Add(new SelectListItem { Text = "New", Value = "New" });
  Status.Add(new SelectListItem { Text = "PaymentPending", Value = "PaymentPending" });
  Status.Add(new SelectListItem { Text = "PaymentProcessed", Value = "PaymentProcessed" });
  Status.Add(new SelectListItem { Text = "Dispatched", Value = "Dispatched" });
  Status.Add(new SelectListItem { Text = "Complete", Value = "Complete" });
  Status.Add(new SelectListItem { Text = "Cancelled", Value = "Cancelled" });
}
public List<SelectListItem> Status { get; set; }
public string SelectedVal{get;set;}
} 

然后在视图中

@NS.Model
@Html.DropDownListFor(x=> x.SelectedVal, x.Status)

答案 1 :(得分:0)

第一个参数是模型中下拉列表的选定值。第二个值是状态列表。

@Html.DropDownListFor(x=> x.SelectedValue, Model.Status)