剃刀视图中的@ Html.DropDownList问题?

时间:2013-01-31 14:23:46

标签: asp.net asp.net-mvc asp.net-mvc-3 razor asp.net-mvc-4

我有一个回复提交按钮的表单。

我的菜单下拉列表如下:

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

如何在模型中将所选值设置为bool或最好为字符串..

我需要验证

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

请帮忙。

由于

3 个答案:

答案 0 :(得分: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>
}

答案 1 :(得分: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" })

答案 2 :(得分:1)

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

模型中的State属性应为string