Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create an Empty SelectList

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

like image 820
john Gu Avatar asked Jul 16 '14 10:07

john Gu


2 Answers

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.

like image 84
Lapenkov Vladimir Avatar answered Sep 29 '22 17:09

Lapenkov Vladimir


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.

like image 35
Christos Avatar answered Sep 29 '22 18:09

Christos