每个和所有元素的Razor DropDownList

时间:2013-11-04 11:48:11

标签: c# asp.net-mvc razor html-select

有没有办法用Razor创建DropDownList并将第二个参数作为Linq结果而不是默认的空项传递?

关键是我正在使用累加器函数(“函数”),因此我无法将null传递给它(作为该问题的答案 - Alternative for multiple IF/CASE statements

如果DropDownList不合适,我真的很感激另类。

控制器:

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

“过滤”方法:

public virtual IEnumerable<T> Filter(params Expression<Func<T, bool>>[] filters)
        {
            IQueryable<T> query = dbSet;

            return filters.Aggregate(query, (a, b) => a.Where(b));
        }

查看:

@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 个答案:

答案 0 :(得分:0)

Filter方法使用需要参数的委托来构造Linq查询。

问题是DDL传递null是因为在DDL中选择“All”项目。因为Linq得到了一个null,所以像n =&gt;这样的表达式n.Name == null显然不起作用。

为了处理空参数,我使用了链接问题的CodeMaster提示:

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