@ Html.DropDownList razor problem?
I have a form that responds to a submit button.
I have a dropdown in the menu:
@Html.DropDownList("State", new List<SelectListItem>
{
new SelectListItem { Text = "Please select" },
new SelectListItem { Value = "AL", Text="Alabama" }, ....
new SelectListItem { Value = "WY", Text="Wyoming" })
How can I get the selected value as a bool or preferably as a string in my model.
I need to check
[Required(ErrorMessage = "Please select a state.")]
public string/bool State { get; set; }
Please, help.
thank
You want to use a helper for the model
@model MVC4.Models.Model
and then
@Html.DropDownListFor(m=>m.State, new List<SelectListItem>
new SelectListItem { Text = "Please select" },
new SelectListItem { Value = "AL", Text="Alabama" }, ....
new SelectListItem { Value = "WY", Text="Wyoming" })
How to get the selected value as bool
It's too hard to bind a state name to a boolean variable.
Use the line instead:
public class MyViewModel
{
[Required(ErrorMessage = "Please select a state.")]
public string State { get; set; }
}
then you can have a controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// there was a validation error - probably the user didn't select a state
// => redisplay the view so that he can fix the error
return View(model);
}
// at this stage the model is valid
// you could use the model.State property that will hold the selected value
return Content("Thanks for selecting state: " + model.State);
}
}
and finally you get the corresponding strongly typed view:
@model MyViewModel
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.State)
@Html.DropDownListFor(
x => x.State,
new[]
{
new SelectListItem { Text = "Please select" },
new SelectListItem { Value = "AL", Text="Alabama" },
.....
new SelectListItem { Value = "WY", Text="Wyoming" }
},
"-- select a state --"
)
@Html.ValidationMessageFor(x => x.State)
</div>
<button type="submit">OK</button>
}
For the "Please Select" element, you need to set it to an empty string. If you don't, IIRC, Value
and Text
will render the same (which is why your required validator assumes there is a value).
The property State
in your model should be string
.