简体   繁体   中英

How to solve this Error Cannot implicitly convert type?

I'm receiving an error in controller in line model.dropdownuserlist :

System.Collections.Generic.List<System.Web.Mvc.SelectListItem> to System.Collections.Generic.List<System.Web.WebPages.Html.SelectListItem>

My model is like below

 public List<SelectListItem> dropdownuserlist { get; set; }

 [Display(Name = "Select User")]
 public string uid { get; set; }    

and controller is dropdown.cs .

 public ActionResult Dropdown()
 {
     DropdownModel model = new DropdownModel();

     model.dropdownuserlist = dropdownuserlist()
         .Select(p => 
             new SelectListItem 
             { 
                 Text = p.Name, 
                 Value = p.Id.ToString() 
             })
         .ToList<SelectListItem>();
     return View();
 }

I can not figure out how to cast this properly. Any suggestions?

Try

model.dropdownuserlist = dropdownuserlist().Select(p => new System.Web.WebPages.Html.SelectListItem { Text = p.Name, Value = p.Id.ToString() }).ToList();

You are using the wrong namespace.

It looks like you are having a class ambiguity problem being caused by your referenced namespaces. There are 3 ways to deal with this.

  1. Check your using statements and remove the conflicting namespace if possible.
  2. Try using the fully qualified name in your code, ie System.Web.Mvc.SelectListItem.
  3. If you must have using statements for both namespaces, it is possible to use a couple of using statements to create aliases and reference the alias in your code.

See using Directive (C# Reference) for an example of using aliases.

using HtmlSelectListItem = System.Web.WebPages.Html.SelectListItem ;
using MVCSelectListItem = System.Web.Mvc.SelectListItem;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM