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?
Try this:
@Html.DropDownListFor(modelItem => modelItem.CheckerApproved, new [] { new SelectListItem { Text = "True", Value="1" } , new SelectListItem { Text = "False", Value="0"} })
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With