Question

I'm populating a dropdownlist of years using the following controller. Instead of listing years manually, I want to retrieve a list from the database. I created a linq query and have returned the years to a list, but I can't figure out how to get that list into the one being passed.

    public JsonResult PopulateYears()
    {
        var list = new object[] { };

        list = new object[] {
            new { value = 2001, name = "2001" },
            new { value = 2002, name = "2002" },
            new { value = 2003, name = "2003" }
        };

        var results = dbBudget.Estimates.Select(o => o.Year).Distinct().ToList();

        foreach (var result in results)
        {
            //How do I create entries for list here?
        }

        return Json(list);
    }
Was it helpful?

Solution

you could create an anonomus type like such

var list = (from x in dbBudget.Estimates.Select(o => o.Year).Distinct()
select new {value=x.Year,name = x.Year});

and then just use your line

return Json(list);

the result will be

[{"name":"2011","value":"2011"},{"name":"2012","value":"2012"},{"name":"2010","value":"2010"}]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top