I have this dropdownlist in a view:
@Html.DropDownList("Sale.TypeTransaction", ViewBag.typetransaction as SelectList, new { @class = "form-control" })
As you can see, the name of the dropdownlist is Sale.TypeTransaction
because Sale
it's a model inside a custom model:
public class OfficeSale
{
public OfficeSale()
{
SaleProductRelations = new List<SaleProductRelation>();
Sale = new Sale();
}
public Sale Sale { get; set; }
public List<SaleProductRelation> SaleProductRelations { get; set; }
}
Sale
has the property TypeTransaction
, it is a string
. In my controller I fill the selectlist as follows:
public ActionResult NewSale()
{
var list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "Cash", Value = "Cash" });
list.Add(new SelectListItem { Text = "Credit", Value = "Credit" });
list.Add(new SelectListItem { Text = "Promotion", Value = "Promotion" });
ViewBag.typetransaction = list;
return View(new OfficeSale());
}
I know if my viewbag has the same name of my property the dropdownlist is filled. But I cannot Write ViewBag.sale.typetransaction
. Do you have any idea to solve this? Thanks in advance.
OK I tried the following as @StephenMuecke suggested and it worked:
public ActionResult NewSale()
{
var list = new List<string>();
list.Add("Cash");
list.Add("Credit");
list.Add("Promotion");
ViewBag.typetransaction = new SelectList(list);
return View(new OfficeSale());
}
@Html.DropDownList("Sale.TypeTransaction", ViewBag.typetransaction as SelectList, new { @class = "form-control" })
ViewBag.typetransaction as SelectList
this bothers me a lot.
As the DropDownList
helper expects the second parameter to be an IEnumerable
(I believe you are calling this constructor https://msdn.microsoft.com/en-us/library/dd470380%28v=vs.118%29.aspx ) you might need to cast to IEnumerable<SelectListItem>
instead.
Your problem is that in the controller your assign ViewBag.typetransaction
to typeof IEnumerable<SelectListItem>
but then in the view you try and cast it to typeof SelectList
which results in ViewBag.typetransaction
being null
.
SelectList
is IEnumerable<SelectListItem>
( SelectList
derives from MultiSelectList
which derives from IEnumerable<SelectListItem>
) but IEnumerable<SelectListItem>
is not SelectList
There a 2 options to solve this. First, in the view, cast the ViewBag
property to the correct type in the html helper
@Html.DropDownList("Sale.TypeTransaction", ViewBag.typetransaction as IEnumerable<SelectListItem>, new { @class = "form-control" })
or alternatively, in the view, create a SelectList
, for example
ViewBag.typetransaction = new SelectList(new List<string>() { "Cash", "Credit", "Promotion" });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.