Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC DropDownListFor basic True False in View

Tags:

asp.net-mvc

I'm trying to setup a basic DropDownListFor in MVC:

@Html.DropDownListFor(modelItem => item.CheckerApproved, new SelectList(new SelectListItem { Text = "True", Value="1" } , new SelectListItem { Text = "False", Value="0"}))

This is in my view and what I'm wanting is a basic dropdown of true and false with values of 1 and 0 respectively.

I'm thinking the part I have wrong is adding the items to the SelectList constructor.

Can somebody help me with this?

like image 428
AnonyMouse Avatar asked Oct 06 '11 01:10

AnonyMouse


4 Answers

Try this:

@Html.DropDownListFor(modelItem => modelItem.CheckerApproved, new [] { new SelectListItem { Text = "True", Value="1" } , new SelectListItem { Text = "False", Value="0"} })
like image 65
Bennor McCarthy Avatar answered Nov 02 '22 19:11

Bennor McCarthy


For something like this, why don't you simply just emit a Select tag with Options in your view ?

<select id='ddlTrueFalse' name='ddlTrueFalse'>
  <option value='1'>True</option>
  <option value='0'>False</option>
</select>

Then in your Action add the parameter:

public ActionResult MyAction(string ddlTrueFalse)
{
  //ddlTrueFalse will be "1" or "0"
}

I've had to do a few of these, and I actually wrote this as an extension method to HtmlHelper, but its a lot cleaner, its easy to debug and it's faster for the site in general.

like image 3
Russ Clarke Avatar answered Nov 02 '22 17:11

Russ Clarke


This already exists -- if you do Html.EditorFor(model => model.MyBoolean) you will get a drop down list with True/False and a default of Unset or similar.

like image 2
Cymen Avatar answered Nov 02 '22 17:11

Cymen


I had a hard time figuring out how to add a "class" to the code above, so I shared this, had to put original dropdown list in brackets, then add an overload

@Html.DropDownListFor(modelItem => modelItem.CheckerApproved, (new[] { new SelectListItem { Text = "True", Value = "1" }, new SelectListItem { Text = "False", Value = "0" } }), new { @class = "form-control" } )


@Html.DropDownListFor(modelItem => modelItem.CheckerApproved, (new[] { new SelectListItem { Text = "Selected", Value = "1" }, new SelectListItem { Text = "Not Selected", Value = "0" } }), new { @class = "form-control" } )

I add this as additional info, as it allows the designed to choose the name of the drop down option while allowing the programming team to still force a bool. Separation of form from design.

like image 1
ransems Avatar answered Nov 02 '22 17:11

ransems