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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With