john G john G - 1 month ago 43
ASP.NET (C#) Question

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

Answer

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.