繁体   English   中英

我如何仅过滤和搜索选定字段并排除 ASP.NET MVC 中的 null 文本框

[英]How do i filter and search selected fields only and exclude null textboxes in ASP.NET MVC

只是我有 4 个文本框,我想通过一个或两个或 3 或 4 个文本框搜索和过滤数据,如果我不想通过该文本框搜索,则排除该文本框:

我正在使用 entityFramework,并且我的 orders_class 包括表 Lab_Orders、Lab_Sample_status、Patients:

我拥有的领域:

开始日期 - - - - - - - -

结束日期 - - - - - - - - -

综合医院档案号 -------------

身份证或护照号码 --------------

I select 数据取决于在文本框字段中输入的值

我想有时只搜索两个日期(开始日期到结束日期)之间的订单。

有时我需要按患者护照号码搜索所有订单

有时我需要通过综合诊所文件搜索

1-我创建了视图输入文本框:

@using (Html.BeginForm("Clinicsorders", "Orders", FormMethod.Get))
{
    <span id="FromDate">From Date</span><input id="FromDatetext" type="text" name="startdate"/>
    <span id="ToDate"> To Date</span>    <input id="ToFatetext" type="text" name="enddate"/>
    <span id="PCfileno">Polyclinic File No</span><input id="pcfilenotext" type="text" name="pcfileno" />
    <span id="IDNO">ID/Iqama No</span>    <input id="idnotext" type="text" name="idno" />
    <br/>
    <br/>
    <input id="Submit1" type="submit" value="Search Orders" style="margin-left:1000px" />
}

2-我创建了 controller:

public ActionResult Clinicsorders(DateTime? startdate,DateTime? enddate,string pcfileno,string idno)
        {


            List<Lab_Orders> Clinicorder = db.Lab_Orders.OrderByDescending(x => x.ORDER_ID).ToList();
            List<Lab_Sample_status> samplestatus = db.Lab_Sample_status.ToList();
            List<Patients> patients = db.Patients.ToList();
            if (startdate == null && enddate == null && pcfileno == null && idno == null)
            {
                var OrdersList = from o in Clinicorder
                                 join st in samplestatus on o.order_status equals st.status_id
                                 join pt in patients on o.patient_no equals pt.Patient_No
                                 where o.CUSTID == (int)Session["UserCustid"]
                                 select new Orders_Tables { LabOrders = o, LabOrderStatus = st , patients = pt };
                                 return View(OrdersList);
            }
            else if (startdate != null || enddate != null || pcfileno !=null || idno != null)
            {
                var OrdersList = from o in Clinicorder
                                 join st in samplestatus on o.order_status equals st.status_id
                                 join pt in patients on o.patient_no equals pt.Patient_No
                                 where o.CUSTID == (int)Session["UserCustid"] && (o.ORDER_DATE >= startdate && o.ORDER_DATE <= enddate)
                                 select new Orders_Tables { LabOrders = o, LabOrderStatus = st , patients = pt };
                return View(OrdersList);
            }

            return View();


        }

当我运行视图时默认选择所有订单。

我现在也可以在 2 个日期(开始日期和结束日期)之间成功搜索和过滤。

我现在希望其余部分按字符串值 pcfileno 和 idno 过滤和搜索。

我将如何实现此功能并仅按我需要的数据进行过滤和搜索,并排除 null 文本框。

在 ASP.NET 我之前实现了这个过滤器,如下代码:

protected void BtnSearch_Click(object sender, EventArgs e)
        {
            if (Session["custid"] != null && Convert.ToInt32(Session["custid"]) > 0)
            {
                string sql = @"SELECT [LAB_RESULTS].ORDER_ID  as 'order number'
       ,APPROVED_DATE as 'Report Date'
       ,labtests.TestId as 'Test Id'  
       ,labtests.TestName as 'Test_Name'  
       ,labtests.culture as 'Culture' 
       ,CASE WHEN coalesce([RESULT_NUMBER],'') <> '' THEN RESULT_NUMBER WHEN coalesce(RESULT_REPORT, '') <> '' THEN RESULT_REPORT END AS Result  
       ,LAB_RESULTS.CUSTID as 'Customer No'
      ,Customers.CustName as 'Customer Name'
      ,LAB_RESULTS.patient_no as 'Patient No'
      ,Patients.PATIENT_NAME as 'Patient Name'
      ,patientcat.CatName as 'Category'
      ,Patients.Age AS 'AGE'
      ,gender.gendername as 'SEX'
      ,LAB_RESULTS.deptid AS 'DEPTID'
      ,TestsRanges.LowerLimit as 'Low Range'
      ,TestsRanges.UpperLimit as 'High Range'
      ,TestsRanges.text_range as 'Text Range'
      ,Lab_Hematology_Samples.COLLECTION_DATE as 'Collection Date'
      ,LAB_RESULTS.REQ_FORM_NO as 'REQ FORM NUMBER'


  FROM [dbo].[LAB_RESULTS]
  inner join LabTests on LabTests.testid=LAB_RESULTS.TESTID
    inner join TestsRanges on TestsRanges.TestId = LAB_RESULTS.TESTID
  inner join PatientCat on patientcat.CatId = TestsRanges.CatId
  inner join Customers on Customers.CustId=LAB_RESULTS.CUSTID
  inner join patients on Patients.Patient_No = LAB_RESULTS.patient_no
  inner join gender on gender.genderid = Patients.Gender
  inner join Lab_Orders on Lab_Orders.ORDER_ID = LAB_RESULTS.ORDER_ID
  inner join Lab_Hematology_Samples on Lab_Hematology_Samples.ORDER_ID = LAB_RESULTS.ORDER_ID

  where lab_results.deptid =1
  and   (Lab_Orders.catid = TestsRanges.CatId or PatientCat.CatId =5)
  and  LAB_RESULTS.EXAMINED_DATE is not null 
  and  LAB_RESULTS.APPROVED_DATE is not null
  and LAB_RESULTS.update_count in (select max(update_count) from LAB_RESULTS A where A.SAMPLE_STATUS = 6 and A.deptid=LAB_RESULTS.DEPTID  and A.ORDER_ID = LAB_RESULTS.ORDER_ID)
  and  (Patients.Gender = TestsRanges.PatientSex or TestsRanges.PatientSex = 1 )
  AND TestsRanges.machine_id = LAB_RESULTS.machine_id  ";

                string condition = "";
                string orderby = "";
                condition += " and LAB_RESULTS.custid ='" + Session["custid"] + "'";
                orderby += "order by LAB_RESULTS.ORDER_ID desc";
                if (DropDownTest.SelectedValue != "")
                {
                    condition += " and labtests.TestId ='" + DropDownTest.SelectedValue + "'";
                }

                if (TxtPatientNo.Text != "")
                {
                    condition += " and LAB_RESULTS.patient_no='" + TxtPatientNo.Text + "'";
                }

                if (txtreq.Text != "")
                {
                    condition += " and LAB_RESULTS.REQ_FORM_NO='" + txtreq.Text + "'";
                }

                if (TxtFromDate.Text != "")
                {
                    string date_day = Convert.ToDateTime(TxtFromDate.Text).Day.ToString();
                    string date_month = Convert.ToDateTime(TxtFromDate.Text).Month.ToString();
                    string date_year = Convert.ToDateTime(TxtFromDate.Text).Year.ToString();
                    string date = date_month + "/" + date_day + "/" + date_year;
                    condition += " and Lab_Hematology_Samples.COLLECTION_DATE > '" + date + "'";
                }

                if (TxtToDate.Text != "")
                {
                    string date_day = Convert.ToDateTime(TxtToDate.Text).Day.ToString();
                    string date_month = Convert.ToDateTime(TxtToDate.Text).Month.ToString();
                    string date_year = Convert.ToDateTime(TxtToDate.Text).Year.ToString();
                    string date = date_month + "/" + date_day + "/" + date_year;
                    condition += " and Lab_Hematology_Samples.COLLECTION_DATE <  '" + date + "'";
                }


                DataTable dt = func.fireDatatable(string.Format(sql + condition + orderby));
                GridView1.DataSource = dt;
                GridView1.DataBind();
            } 

我将如何在 MVC 和 linq 中实现相同的功能

如果 pcfileno 文本框 != null 然后搜索

如果 idno 文本框?= null 然后搜索?

假设您正在使用 EntityFramework 并且 LazyLoading 被禁用并且您的实体具有导航属性Lab_Sample_StatusPatient ,您可以像 ff 一样使用IQueryable

int custId = (int)Session["UserCustid"];
// eager load navigation properties
// query is IQueryable
var query = db.Lab_Orders.Include("Lab_Sample_Status").Include("Patient").Where(r => r.CUSTID == custId);

if (startdate.HasValue && enddate.HasValue)
{
    query = query.Where(r => DbFunctions.TruncateTime(r.Lab_Sample_Status.CollectionDate) >= DbFunctions.TruncateTime(startdate.Value) && 
        DbFunctions.TruncateTime(r.Lab_Sample_Status.CollectionDate) <= DbFunctions.TruncateTime(enddate.Value));
}

if (!string.IsNullOrEmpty(pcfileno))
{
    query = query.Where(r => r.Lab_Sample_Status.PcFileNo == pcfileno);
}

if (!string.IsNullOrEmpty(idno))
{
    query = query.Where(r => r.Patient.PatientNo == idno);
}

// .. You can continue to manipulate the query

// db results is determined upon calling ToList()
var model = query.ToList().Select(r => new Orders_Tables() { LabOrders = r, LabOrderStatus = r.Lab_Sample_Status, Patient = r.Patient });

return View(model);

如果您没有上述导航属性,则可以执行以下操作:

int custId = (int)Session["UserCustid"];
// query is IQueryable
var query = db.Lab_Orders.Where(r => r.CUSTID == custId)
                .Join(db.Lab_Sample_Status, order => order.order_status, status => status.status_id, (order, status) => new { Order = order, Status = status })
                .Join(db.Patients, rec => rec.Order.patient_no, patient => patient.Patient_No, (rec, patient) => new Orders_Tables { LabOrders = rec.Order, LabOrderStatus = rec.Status, patients = patient });

if (startdate.HasValue && enddate.HasValue)
{
    query = query.Where(r => DbFunctions.TruncateTime(r.LabOrderStatus.CollectionDate) >= DbFunctions.TruncateTime(startdate.Value) && 
        DbFunctions.TruncateTime(r.LabOrderStatus.CollectionDate) <= DbFunctions.TruncateTime(enddate.Value));
}

if (!string.IsNullOrEmpty(pcfileno))
{
    query = query.Where(r => r.LabOrderStatus.PcFileNo == pcfileno);
}

if (!string.IsNullOrEmpty(idno))
{
    query = query.Where(r => r.patients.Patient_No == idno);
}

// db results is determined upon calling ToList()
var model = query.ToList();

return View(model);

PS:我很犹豫是否将其发布为答案,因为 OP 的问题不够清楚,但评论部分已经有点长了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM