Where Statement MVC中的可选条件4

时间:2016-01-21 20:53:02

标签: 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
    {

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

因此,如果你看一下,用户可以输入许多可选字段。如果他们在该字段中输入数据,则会将其添加到搜索结果中。现在,如果他们输入一个类型和搜索用户,它将打开带有相应数据的页面。但是,我试图解决的问题是,如果他们不输入类型。我不希望搜索结果出现。现在它做到了这一点:

http://localhost:51730/Search/NameSearchList?userName=Admin&type=1

但是我们可以说他们不会搜索名称而只搜索某种类型。如何确保“userName = Admin”不会显示。我想限制每一个如果它们没有输入或NULL并且只输入那些。

您能否展示一下我将如何获得可选要求的解决方案?

谢谢!

1 个答案:

答案 0 :(得分:0)

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