How to create an empty SelectList

I have the following action method:

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); } 

but currently i got the following error on var CustomerData; :

 implicitly typed local variables must be initialized 

so I'm not sure how can I create an empty SelectList to assign it to the var variable? Thanks

+6
source share
6 answers

You can try the following:

 IEnumerable<SelectListItem> customerList = new List<SelectListItem>(); 

The error you received is reasonable because

The var keyword tells the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

Alternatively, you can try the following:

 var customerList = customerlist.Select(m => new SelectListItem() { Text = m.NAME, Value = m.NAME.ToString(), }); 

The reason the second assignment will work is because the compiler can infer the type of the variable in this way, since it knows what type of LINQ query is returned.

+6
source

This error means that you cannot declare a var variable without specifying a value, for example:

 var double1 = 0.0; // Correct, compiler know what type double1 is. var double2; // Error, compiler not know what type double2 is. 

You need to assign the value var CustomerData; , eg:

 var CustomerData = customerlist.Select(m => new SelectListItem() { Text = m.NAME, Value = m.NAME.ToString(), }); 
+4
source

Try the following:

 customerlist = new[] { new SelectListItem { } }; 
+4
source

Use this to create an empty SelectList :

 new SelectList(Enumerable.Empty<SelectListItem>()) 

Enumerable.Empty<SelectListItem>() creates empty sequences to be passed to the SelectList constructor. This is necessary because SelectList does not have a constructor overload without parameters.

+3
source

Initialize a variable when it is declared:

 var CustomerData = customerlist.Select(m => new SelectListItem() { Text = m.NAME, Value = m.NAME.ToString(), }); 
+2
source

empty default list item

 var area = new[] { new tbl_Area { AreaID = -1, AreaName = "Please Select Main Area" } }; 

tbl_Area can be a class or datamodel

  class tbl_Area{ public int AreaID {get;set;} public string AreaName {get;set;} } 
+1
source

Source: https://habr.com/ru/post/972314/


All Articles