How to Create an Empty SelectList
Solution 1
You could try this one:
IEnumerable<SelectListItem> customerList = new List<SelectListItem>();
The error you were getting is reasonable, since
The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.
On the other hand, you could try the following one:
var customerList = customerlist.Select(m => new SelectListItem()
{
Text = m.NAME,
Value = m.NAME.ToString(),
});
The reason why the second assignment will work is that in this way the compiler can infer the type of the variable, since it knows the type of the LINQ query returns.
Solution 2
Use this to create an empty SelectList
:
new SelectList(Enumerable.Empty<SelectListItem>())
Enumerable.Empty<SelectListItem>()
creates an empty sequences which will be passed to the constructor of SelectList
. This is neccessary because SelectList
has no constructor overloading without parameters.
Solution 3
Try this:
customerlist = new[] { new SelectListItem { } };
Solution 4
That error means that you cannot declare a var
variable without giving 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 a value to var CustomerData;
for example:
var CustomerData = customerlist.Select(m => new SelectListItem()
{
Text = m.NAME,
Value = m.NAME.ToString(),
});
Solution 5
Initialise the variable when you declare it:
var CustomerData = customerlist.Select(m => new SelectListItem()
{
Text = m.NAME,
Value = m.NAME.ToString(),
});
john Gu
Updated on June 26, 2022Comments
-
john Gu almost 2 years
I have the folloiwng 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 am not sure how i can create an empty SelectList to assign it to the var variable ? Thanks
-
Mardoxx over 7 yearsHow can you create an instance of an interface?
-
Christos over 7 years@Mardoxx oops...I just noted it and I corrected it.