c# - "There is no ViewData item of type 'IEnumerable<SelectListItem>'" error with custom model and list -


i have dropdownlist in view:

@html.dropdownlist("sale.typetransaction", viewbag.typetransaction selectlist, new { @class = "form-control" }) 

as can see, name of dropdownlist sale.typetransaction because sale it's model inside 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 property typetransaction, string. in controller fill selectlist 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 viewbag has same name of property dropdownlist filled. cannot write viewbag.sale.typetransaction. have idea solve this? in advance.

ok tried following @stephenmuecke suggested , 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 selectlist, new { @class = "form-control" }) 

your problem in controller assign viewbag.typetransaction typeof ienumerable<selectlistitem> in view try , cast typeof selectlist results in viewbag.typetransaction being null.

selectlist ienumerable<selectlistitem> (selectlist derives multiselectlist derives ienumerable<selectlistitem>) ienumerable<selectlistitem> is not selectlist

there 2 options solve this. first, in view, cast viewbag property correct type in html helper

@html.dropdownlist("sale.typetransaction", viewbag.typetransaction ienumerable<selectlistitem>, new { @class = "form-control" }) 

or alternatively, in view, create selectlist, example

viewbag.typetransaction = new selectlist(new list<string>() { "cash", "credit", "promotion" }); 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -