Search code examples
c#asp.net-mvcrazor

How can I select drop down list data depends on condition?


I have tests drop down list.

How can I select the tests in drop down list where DEPT_ID = 12?

I have the table includes the following columns:

DEPT_ID TEST_D 
1        1
1        2
1        3
2        4
2        5
2        6
3        7
4        8
5        9
12       50
12       51
12       52 
12       53 

This is GET Index and Create controller:

public ActionResult Create()
{
    ViewBag.TEST_ID = new SelectList(db.LabTests, "TestId", "TestName");
    return View();
}

public ActionResult Index()
{
    var iNFECTION_DISEASE = db.INFECTION_DISEASE.Where(d=>d.DEPT_ID==12).Include(i => i.Department).Include(i => i.Hospital).Include(i => i.LabTest).Include(i => i.sys_users);
    return View(iNFECTION_DISEASE.ToList());
}

This is TEST_ID .cshtml part of view

 <div class="form-group">
    @Html.LabelFor(model => model.TEST_ID, "TEST_ID", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("TEST_ID", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.TEST_ID, "", new { @class = "text-danger" })
    </div>
</div>

This is the tables declaration :

CREATE TABLE [dbo].[INFECTION_DISEASE](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [DEPT_ID] [int] NULL,
    [TEST_ID] [int] NULL,
    [TOTAL_TESTS] [int] NULL,
    [NEGATIVE] [int] NULL,
    [POSITIVE] [int] NULL,
    [NATIONALITY] [varchar](100) NULL,
    [REGION] [varchar](50) NULL,
    [DATE] [datetime] NOT NULL,
    [hospital_no] [int] NULL,
    [user_id] [int] NULL)

CREATE TABLE [dbo].[LabTests](
    [TestId] [int] IDENTITY(1,1) NOT NULL,
    [TestName] [nvarchar](50) NULL,
    [Dept_id] [int] NULL)

How can I select tests in drop down list where DEPT_ID = 12 only?


Solution

  • The question above does not contain all related parts of code. But I suppose it should be like the following:

    var tests = db.LabTests.Where(lt => lt.DEPT_ID == 12).Select(t => t.Test).ToList();
    ViewBag.TEST_ID = new SelectList(tests, "TestId", "TestName");