MVC - 无法转换为' int'到' system.web.ui.webcontrols.listitem

时间:2017-01-20 15:20:16

标签: c# asp.net linq model-view-controller drop-down-menu

您好我正在尝试提供从多选下拉框中选择客户ID的客户;我的控制器,我有上面提到的错误

public ActionResult Create(CountryViewModel country)
    {
        List<SelectListItem> selectedItems = country.MenuCountry.Where(p => country.ContryIds.Contains(int.Parse(p.Value))).ToList();         
        try
        {
            CustomerClient CC = new CustomerClient();
            var result = CC.findAll();

            var matches = from customer in result
                          where selectedItems.Contains(customer.Id) // Here is error and saying cannot convert from 'int' to 'system.web.ui.webcontrols.listitem
                          select customer;
           // ViewBag.listCustomers = CC.findAll();

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

我的客户课程如下:

public class Customer
{
    [Display(Name = "CustomerId")]
    public int Id { get; set; }
    [Display(Name = "Country")]
    public string Country { get; set; }
}

请指教;非常感谢

2 个答案:

答案 0 :(得分:1)

请试试这个

 var matches = from customer in result
               where selecteList.Exists(a=>a.Value==  customer.Id.ToString())                          select customer;

答案 1 :(得分:0)

假设您的CountryViewModel看起来像这样

public class CountryViewModel 
{
  public List<SelectListItem> MenuCountry{ get; set; } 
  public string[] ContryIds { get; set; } 
}

现在您只需要过滤该国家/地区。只需使用country.ContryIds获取所选的国家/地区ID(实际上是名称)。

 public ActionResult Create(CountryViewModel country)
 {
    var CC = new CustomerClient();
    var result = CC.findAll(); // assuming this return a collection of Customer
    var matches = result.Where(x=>country.CountryIds.Contains(x.Country);
    // to do : return something
 } 

由于Country属性属于string类型,我们需要确保下拉列表的选项值也是字符串(国家/地区(名称)?)。所以可能在您的GET操作中,使用下拉列表呈现视图,

var countryOptions = new List<SelectListItem> {
  new SelectListItem { Value="USA", Text="USA"},
  new SelectListItem { Value="Canada", Text="Cananda" }
};
// to do : pass countryOptions  to the view to render the dropdown