Is there a way to create DropDownList with Razor and pass second parameter as Linq result instead of default empty item?
The key is that I'm using accumulator function ("Function") so I can not pass null into it (as a answer to that question - Alternative for multiple IF/CASE statements)
If DropDownList is not suitable I would really appreciate an alternative.
Controller:
public ActionResult Index(string searchFullName, string searchExtension, string searchProject)
{
var extensionList = new List<string>();
var projectList = new List<string>();
var projects = from n in unitofwork.DomainRepository.Get()
select n.Project;
var extensions = from n in unitofwork.DomainRepository.Get()
select n.Extension;
extensionList.AddRange(extensions.Distinct());
projectList.AddRange(projects.Distinct());
ViewBag.searchproject = new SelectList(projectList);
ViewBag.searchExtension = new SelectList(extensionList);
return View(unitofwork.DomainRepository.Filter(n => n.Name.Contains(searchFullName), n => n.Extension == searchExtension));
}
"Filter" method:
public virtual IEnumerable<T> Filter(params Expression<Func<T, bool>>[] filters)
{
IQueryable<T> query = dbSet;
return filters.Aggregate(query, (a, b) => a.Where(b));
}
View:
@using (Html.BeginForm()) {
<p>
Name: @Html.TextBox("searchFullName")
Extension: @Html.DropDownList("searchExtension", "All") <- *would like to get one extension or all extensions*
Projects: @Html.DropDownList("searchProject","All")
<input type="submit" value="Filters" />
</p> }
Filter method uses delegates that need parameter to construct Linq query.
The problem was that DDL was passing null as result for selecting "All" items in DDL. Because of that Linq was getting a null so expressions like n => n.Name == null obviously didn't work.
To deal with null parameters I used CodeMaster's hint from linked question :