In MVC.
I am getting this error message when trying to display a dropDownList in Razor.
DataBinding: 'System.Int32' does not contain a property with the name 'BranchId'.
In the watch window I am able to see 1 record is being returned from the database containing a BranchId
and BranchName
I have no reference to the SelectList
in the Model class.
In the Controller class
var list = new SelectList(db.Branchs.Where(branches => !db.CompanyBranches
.Any(d => d.BranchId == branches.BranchId))
.Select(branches => branches.BranchId).ToList(),
"BranchId", "BranchNumber");
ViewBag.Branch = new SelectList(list);
In the Create.cshtml
@Html.DropDownList("Branch", new SelectList(ViewBag.Branch, "BranchID", "BranchName"), htmlAttributes: new { @class = "form-control" })
Thanks Stephen
I changed the lambda expression in my CompanyBranchesController as you suggested it is now var list = db.Branchs.Where(branches => !db.CompanyBranches .Any(d => d.BranchId == branches.BranchId)) .Select(b => new { BranchId = b.BranchId, BranchName = b.BranchName }).ToList();
The Create.cshtml for the dropdownlist is @Html.DropDownList("Branch", ViewBag.Branch as IEnumerable, htmlAttributes: new { @class = "form-control" })
The result in the dropdownlist is {BranchId = 5, BranchNumber = Br0003}
I have been playing with it including adding to the CompanyBranchController
List items = new List();
foreach (var i in list)
{
SelectListItem s = new SelectListItem();
s.Text = i.BranchName.ToString();
s.Value = i.BranchId.ToString();
items.Add(s);
}
As well as trying different razor expressions but with no success.
Any Idea where I am going wrong?