C# Where语句MVC 4中的可选条件

C# Where语句MVC 4中的可选条件,c#,asp.net-mvc,database,asp.net-mvc-4,C#,Asp.net Mvc,Database,Asp.net Mvc 4,我有一个模型: using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ReviewLogs.Models { public class SearchModel { [Dis

我有一个模型:

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace ReviewLogs.Models
{
    public class SearchModel
    {

        [Display(Name = "Type: ")]
        public int? type { get; set; }

        [Display(Name = "Server: ")]
        public string curServer { get; set; }

        [Display(Name = "Status: ")]
        public string status { get; set; }

        [Display(Name = "User Name: ")]
        public string searchedUser { get; set; }


        [Display(Name = "Month Ending: ")]
        public int? monthEnd { get; set; }

        [Display(Name = "Year Ending: "),
        RegularExpression("^([0-9]{4})$", ErrorMessage = "Year must be entered and a valid 4 digit number")]
        public int? yearEnd { get; set; }

        [Display(Name = "Min Log Date: ")]
        public string minLogDate { get; set; }

        [Display(Name = "Max Log Date: ")]
        public string maxLogDate { get; set; }



        [Display(Name = "Ticket Number: ")]
        public string ticket { get; set; }


        [Display(Name = "Comment: ")]
        public string comment { get; set; }

        public SearchModel()
        {
            searchedUser = " ";
        }
    }
}
控制器:

        public ActionResult LogSearch()
        {
            if (Request.IsAuthenticated)
            {
                loadDropDown();
                return View();

            }
            else
            {
                return RedirectToAction("index", "home");
            }
        }

        [HttpPost]
        public ActionResult LogSearch(SearchModel submission)
        {
            loadDropDown();




            return RedirectToAction("NameSearchList", "Search", new { userName = submission.searchedUser ,type = submission.type.Value});


        }

public ActionResult NameSearchList(int? type, string userName = "")
        {


                var cnn = new reviewlogsEntities();

                return View(cnn.logrecords.Where(m => m.username == userName && m.typeid == type));




        }
还有一个观点:

    @model ReviewLogs.Models.SearchModel

@{
    ViewBag.Title = "Add Review";
}

@section Scripts{
    <script src="~/Scripts/jquery-1.12.0.min.js"></script>
    <script src="~/Scripts/datetimepicker_css.js"></script>
    <script src="~/Scripts/CurDropDownChecker.js"></script>

}


}


<h2>Add Review</h2>
@Html.ValidationSummary(true, "Submission Failed, Please Try Again")
<p id="success">@ViewBag.SuccessMessage</p>
<div class="formBody">

    @using (Html.BeginForm())
    {
        <div class="inputOthers">
            @Html.LabelFor(model => model.type)
            @Html.DropDownList("type", ViewBag.type as IEnumerable<SelectListItem>, "", new { onchange = "setDisplay();" })
            @Html.ValidationMessageFor(model => model.type)
        </div>
    <div class="inputOthers">
        @Html.LabelFor(model => model.searchedUser)
        @Html.DropDownList("searchedUser", ViewBag.users as IEnumerable<SelectListItem>, " ")

    </div>
        <div class="inputOthers">
            @Html.LabelFor(model => model.curServer)
            @Html.DropDownList("curServer", ViewBag.server as IEnumerable<SelectListItem>, " ")

        </div>

        <div class="inputOthers">
            @Html.LabelFor(model => model.status)
            @Html.DropDownList("status", ViewBag.status as IEnumerable<SelectListItem>, " ")

        </div>

        <div class="inputOthers">
            @Html.LabelFor(model => model.ticket)
            @Html.TextBoxFor(model => model.ticket)

        </div>
        <div class="inputOthers">
            @Html.LabelFor(model => model.comment)
            @Html.TextAreaFor(model => model.comment, new { style = "width:320px; height: 160px;" })

        </div>

        <div class="inputOthers">
            @Html.LabelFor(model => model.minLogDate)
            @Html.TextBoxFor(model => model.minLogDate, new { @readonly = "readonly" })

            <a href="javascript: NewCssCal('logDate','mmddyyyy','arrow',true,12)">
                <img src="~/Images/cal.gif" width="16" height="16" alt="Pick a date">
            </a>

        </div>

     <div class="inputOthers">
        @Html.LabelFor(model => model.maxLogDate)
        @Html.TextBoxFor(model => model.maxLogDate, new { @readonly = "readonly" })

        <a href="javascript: NewCssCal('logDate','mmddyyyy','arrow',true,12)">
            <img src="~/Images/cal.gif" width="16" height="16" alt="Pick a date">
        </a>

     </div>

        <div class="inputOthers">
            <span id="monthEnd">

                @Html.LabelFor(model => model.monthEnd)
                @Html.DropDownListFor(model => model.monthEnd, ViewBag.months as IEnumerable<SelectListItem>, " ")

            </span>

            <span id="yearEnd">
                @Html.LabelFor(model => model.yearEnd)
                @Html.TextBoxFor(model => model.yearEnd, new { @Value = DateTime.Now.Year })

            </span>


        </div>
        <input class="submitButton" type="submit" value="Submit" style="margin-left:126px;margin-bottom: 20px;" onclick="return confirm('If you would like to submit press OK');" />

    }
</div>
但假设他们不搜索名称,只搜索类型。如何确保“userName=Admin”不会出现。我想限制每一个,如果他们没有输入或空,只有那些输入

你能不能给我一个解决方案,让我看看我是如何满足可选需求的


谢谢

在NameSearchList操作中添加忽略空值的条件筛选器有两个选项

选项1:在where语句中检查空值

var q = cnn.logrecords.Where(m => (m.username == userName || string.IsNullOrEmpty(userName)) && (m.typeid == type || !type.HasValue))
return View(q);
选项2:仅为那些非空参数添加where语句

var q = cnn.logrecords;
if(!string.IsNullOrEmpty(userName))
{
    q = q.Where(m => m.username == userName);
}
if(type.HasValue)
{
    q = q.Where(m => m.typeid == type);
}
return View(q);
我建议您查看指导并清理您帖子中的代码,这样只剩下最少的相关代码。目前,代码使得文章很长,糟糕的格式并不能改善访问者的印象,这可能会导致人们忽视这个问题,并可能对它投否决票。
var q = cnn.logrecords;
if(!string.IsNullOrEmpty(userName))
{
    q = q.Where(m => m.username == userName);
}
if(type.HasValue)
{
    q = q.Where(m => m.typeid == type);
}
return View(q);