3

我有一个响应提交按钮的表单。

我在菜单上有我的下拉列表,如下所示:

@Html.DropDownList("State", new List<SelectListItem>
{
    new SelectListItem { Text = "Please select" }, 
    new SelectListItem { Value = "AL", Text="Alabama" }, ....
    new SelectListItem { Value = "WY", Text="Wyoming" })

如何在我的模型中将选定的值作为布尔值或最好作为字符串..

我需要验证

[Required(ErrorMessage = "Please select a state.")]
public string/bool State { get; set; }

请帮忙。

谢谢

4

3 回答 3

3

如何将选定的值作为 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>
}
于 2013-01-31T14:46:59.553 回答
2

您想使用模型绑定助手

@model MVC4.Models.Model

进而

@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" })
于 2013-01-31T14:30:12.123 回答
1

对于“请选择”项,您需要设置一个空字符串的值。如果你不这样做,IIRC,ValueText将呈现相同的(所以你需要的验证器认为有一个值)。

模型中的State属性应该是string.

于 2013-01-31T14:29:40.137 回答