我有folloiwng动作方法:
- public JsonResult LoadSitesByCustomerName(string customername)
- {
- var customerlist = repository.GetSDOrg(customername)
- .OrderBy(a => a.NAME)
- .ToList();
- var CustomerData;
- CustomerData = customerlist.Select(m => new SelectListItem()
- {
- Text = m.NAME,Value = m.NAME.ToString(),});
- return Json(CustomerData,JsonRequestBehavior.AllowGet);
- }
但目前我在var CustomerData上遇到以下错误;:
- implicitly typed local variables must be initialized
所以我不知道如何创建一个空的SelectList来将其分配给var变量?
谢谢
解决方法
你可以尝试这个:
- IEnumerable<SelectListItem> customerList = new List<SelectListItem>();
你得到的错误是合理的,因为
The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.
另一方面,您可以尝试以下方法:
- var customerList = customerlist.Select(m => new SelectListItem()
- {
- Text = m.NAME,});
第二个赋值将起作用的原因是,编译器可以通过这种方式推断变量的类型,因为它知道LINQ查询的类型返回.