Reputation: 1
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
Upvotes: 16
Views: 22710
Reputation: 3218
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.
Upvotes: 36
Reputation: 53958
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.
Upvotes: 11
Reputation:
empty list item with default one
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;}
}
Upvotes: 1
Reputation: 1244
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(),
});
Upvotes: 4
Reputation: 604
Initialise the variable when you declare it:
var CustomerData = customerlist.Select(m => new SelectListItem()
{
Text = m.NAME,
Value = m.NAME.ToString(),
});
Upvotes: 2