Razor DropDownList for each and all elements

夙愿已清 提交于 2019-12-25 04:32:15

问题


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> }

回答1:


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 :

return View(unitofwork.DomainRepository.Filter(n => n.Name.Contains(searchFullName), n => (String.IsNullOrEmpty(searchExtension) || n.Extension == searchExtension), n => (String.IsNullOrEmpty(searchProject) || n.Project == searchProject)));


来源:https://stackoverflow.com/questions/19767115/razor-dropdownlist-for-each-and-all-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!