I am trying to use the result of a LINQ Query to populate a SelectList in a MVC 5 application. The LINQ query returns customer IDs.
Model
public partial class Pricelist
{
public int CustomerID { get; set; }
public int SelectedCustomer { get; set; }
public Pricelist(int customerID, int selectedCustomer)
{
}
}
View
@Html.DropDownList("custList")
Controller (1)
var query = ((from s in db.Pricelists
select s.CustId).Distinct()).ToList();
int i = 1;
List<Pricelist> CustomerList = new List<Pricelist>();
foreach (var c in query)
{
int cust = c;
Pricelist p = new Pricelist(i, cust);
CustomerList.Add(p);
i++;
}
SelectList custList = new SelectList(CustomerList);
ViewBag.custList = custList;
return View();
Which returns a drop down populated with the Model class name (I get an exception if I try to return i and cust .ToString() in the foreach.) I tried this because the Controller method below produced the list of distinct CustomerIDs, but returned NULL when it was POSTed (I think because there was no Value specified in the SelectList)
public ActionResult Create()
{
var query = (from s in db.Pricelists
select s.CustId).Distinct();
SelectList CustomerList = new SelectList(query);
ViewBag.custList = CustomerList;
return View();
}
Pointers to where I am going wrong, and how to proceed much appreciated.
Language-Integrated Query (LINQ) makes it easy to access database information and execute queries. By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.
LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.
The Any method checks whether any of the element in a sequence satisfy a specific condition or not. If any element satisfy the condition, true is returned.
The easiest method is to let Razor worry about the SelectList
and just feed it an IEnumerable<SelectListItem>
.
ViewBag.custList = CustomerList.Select(m => new SelectListItem { Value = m.Id, Text = m.Name });
Then in your view:
@Html.DropDownListFor(m => m.SomeField, (IEnumerable<SelectListItem>)ViewBag.custList)
You can make that nicer by using a view model that you can strongly type instead of ViewBag
. You should really avoid ViewBag
as much as possible.
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