Reputation: 3823
I have a class like this:
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");
}
My action:
public ActionResult Index()
{
var model = new MyClass();
return View(model);
}
And the view looks like this:
@Html.DropDownListFor(m => m.saleRange, (IEnumerable<SelectListItem>)Model.saleRange,new { @class= "select2" , @style = "width:95%;border-left:2px solid #eee" })
But I'm getting this error:
Unable to cast object of type 'ServiceStack.Html.SelectList' to type 'System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]'.
What am I doing wrong here? How can I populate the dropdownlist from my viewmodel with hardcoded values??
Upvotes: 1
Views: 5327
Reputation: 10818
Change your model to the following (note that the SelectList
class needs to be from namespace System.Web.Mvc
, not 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");
}
And change your view to:
@Html.DropDownListFor(model => model.SelectedSalesRange, SaleRange, "--- Select date range ---")
If you want to use ServiceStack, then the entire nature of your question is invalid and you need to edit or ask a new question. You have only asked about MVC5
Upvotes: 4
Reputation: 239350
SelectList
is not the same thing as IEnumerable<SelectListItem>
, so there's no way to cast it to that. You could cast saleRange.Items
, as that property of SelectList
is in fact an IEnumerable<SelectListItem>
.
However, that's completely unnecessary in the first place. As saleRange
is a property on your model, it is strongly typed and you don't need to cast it to anything. SelectList
is already a valid type to pass there, so just use saleRange
directly.
Upvotes: 2