如何将选定的值作为 bool
将状态名称绑定到布尔变量几乎没有意义。
改用字符串:
public class MyViewModel
{
[Required(ErrorMessage = "Please select a state.")]
public string State { get; set; }
}
那么你可以有一个控制器:
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);
}
}
最后你会有一个对应的强类型视图:
@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>
}