lou lising
lou lising

Reputation: 71

How to exclude a record from the Drop Down List

I have a drop down list 'Status' on my create view and it gets its data from the database meaning the data on the list are not hard coded but rather dynamic. Currently I have 3 records on the status table (i.e.Available, Unavailable and Cancelled). I want to exclude the Cancelled record so that on the drop down list I will only have Available and Unavailable. The cancelled status is still needed but used in a separate manner. Here are the codes

Controller:

public ActionResult Create(int roomId)
        {
            var room = _db.Rooms.Single(r => r.Id == roomId);
            ViewBag.roomCode = room.RoomCode;
            var statList = _db.ReservationsStatus.ToList();
            var selectList = new SelectList((from s in statList.ToList()
                                             select new { statusId = s.Id, statusName = s.Name }), "statusId", "statusName");

            ViewData["sList"] = selectList;

            return View();
        }

View:

<div class="editor-field">

            @Html.DropDownList("ddStatus", (SelectList)ViewData["sList"])

        </div>        

Any solutions will be appreciated, Thanks.

Upvotes: 1

Views: 2190

Answers (4)

EtherDragon
EtherDragon

Reputation: 2698

Your first step is to determine why "Cancelled" is different from the rest of the statuses. I would suggest adding a column to your database to indicate which of these statuses are shown in the UI.

The problem, as you described, is that with your database able to change at any time, you can't hard-code any particular status to include or exclude, because you may run into data integrity issues.

After adding the column (just a Boolean to the DB, I called it "userSelectable") you can exclude it in your LINQ select statement:

 var selectList = new SelectList((from s in statList.ToList()
                                  select new { statusId = s.Id, statusName = s.Name }
                                  where userSelectable = true), "statusId", "statusName");

Upvotes: 1

Marko
Marko

Reputation: 13233

 var selectList = new SelectList((from s in statList.ToList() where s.Name != "Cancelled" select new { statusId = s.Id, statusName = s.Name }), "statusId", "statusName")

... assuming your Name property is a string and its value is Cancelled...

Upvotes: 1

ravi
ravi

Reputation: 1019

Exclude the required status in the Linq statement through a where clause.

Upvotes: 0

DevProve
DevProve

Reputation: 192

var selectList = new SelectList((from s in statList.Where(x=>x.Name =="Available"||x.Name =="Unavailable") select new { statusId = s.Id, statusName =s.Name }), "statusId", "statusName");

u can also see the Except() method

Upvotes: 1

Related Questions