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

标签 c# asp.net-mvc-3

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

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

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 上查看答案所暗示的那样。但是我得到一个错误:

Compiler Error Message: CS1501: No overload for method 'DropDownListFor' takes 1 arguments

非常感谢任何提示。

最佳答案

错误信息是不言自明的,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;}
} 

然后在 View 中

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

关于c# - 如何在 ASP.NET MVC3 中创建下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9861535/

相关文章:

c# - Windows 手机 7 : Get the name of photo stored in Libary picture?

html - 是否可以以正确的比例渲染两种尺寸的图像

c# - 如何将图像添加到我的 .resx 文件中?

asp.net - 在asp.net MVC中不使用LabelFor Helper获取DisplayName属性

asp.net-mvc-3 - 对于同一型号,我可以从 "shared"编辑器模板中调用 "areas"编辑器模板吗?

c# - 我正在尝试将复选框列表写入数据库,我错过了什么?

c# - 保存 Winform 窗体控件状态的最佳方法?

c# - Azure 应用服务 - .net 版本支持 - 更新(HTTP 500.31 错误)?

c# - 获取 ASP.NET 开发服务器端口号

c# - 为什么派生类中必须保护抽象方法?