使用.NET MVC 5中的硬编码值填充下拉列表

时间:2017-06-22 16:26:06

标签: c# asp.net asp.net-mvc c#-4.0 asp.net-mvc-5

我有一个这样的课程:

public class MyClass
{
     public SelectList saleRange = new SelectList(new[]
            {
                new SelectListItem {  Selected = true ,Text = "--- Select date range ---", Value = "0" },
                new SelectListItem { Selected = false, Text = "7 days", Value = "7" },
                new SelectListItem  { Selected = false, Text = "14 days", Value = "14" },
                new SelectListItem { Selected = false, Text = "21 days", Value = "21" },
                new SelectListItem  { Selected = false, Text = "30 days", Value = "30" },
            }, "Value", "Text");

}

我的行动:

   public ActionResult Index()
        { 
            var model = new MyClass();
            return View(model);
        }

视图如下:

  @Html.DropDownListFor(m => m.saleRange, (IEnumerable<SelectListItem>)Model.saleRange,new { @class= "select2" , @style = "width:95%;border-left:2px solid #eee" })

但是我收到了这个错误:

Unable to cast object of type 'ServiceStack.Html.SelectList' to type 'System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]'.

我在这里做错了什么?如何使用硬编码值从我的viewmodel填充下拉列表

2 个答案:

答案 0 :(得分:3)

将您的模型更改为以下内容(请注意,SelectList需要来自命名空间 System.Web.Mvc,而不是ServiceStack):

public class MyClass
{
    //You need somewhere to put the sales range thats selected
    public string SelectedSalesRange { get; set; }

    public System.Web.Mvc.SelectList SaleRange = new System.Web.Mvc.SelectList(new[]
        {
            //Note that I have removed the "Default" item
            //And the Selected=False (since the default value of a bool is false)

            new System.Web.Mvc.SelectListItem { Text = "7 days", Value = "7" },
            new System.Web.Mvc.SelectListItem  {Text = "14 days", Value = "14" },
            new System.Web.Mvc.SelectListItem { Text = "21 days", Value = "21" },
            new System.Web.Mvc.SelectListItem  { Text = "30 days", Value = "30" },
        }, "Value", "Text");

}

并将您的观点更改为:

@Html.DropDownListFor(model => model.SelectedSalesRange, SaleRange, "--- Select date range ---") 

如果您想使用ServiceStack,则问题的整体性质无效,您需要编辑或提出新问题。您只询问了MVC5

答案 1 :(得分:2)

SelectList IEnumerable<SelectListItem>相同,所以没有办法将其投射到那里。您可以投放saleRange.Items,因为SelectList的属性实际上是IEnumerable<SelectListItem>

然而,这首先是完全没必要的。由于saleRange是您模型上的属性,因此它是强类型的,您不需要将其强制转换为任何内容。 SelectList已经是一种有效的类型,因此请直接使用saleRange