asp.net - @Html.DropDownList Razor View 中的问题?

标签 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; }

请帮忙。

谢谢

最佳答案

How can I get the selected value as bool

将状态名称绑定(bind)到 bool 变量几乎没有意义。

改用字符串:

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

然后你可以有一个 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);
    }
}

最后你会得到一个相应的强类型 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>
}

关于asp.net - @Html.DropDownList Razor View 中的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14628034/

相关文章:

javascript - 如何修复/防止asp.net core View 中的JS代码被转义

c# - 使用 Javascript 在 MVC 中渲染部分 View

asp.net - 将 ASP.NET MVC 混合到 ASP.NET WebForms

asp.net-mvc - 部分 View 的 Razor 部分夹杂物

asp.net - 删除 URL 文件扩展名

javascript - 如何在用户不更改文本框中的文本的情况下强制 .change jquery 事件?

javascript - MVC 部分 View 中的 JQuery/JS?

mysql - MVC3 - 无法将长文本输入数据库

asp.net-mvc - 日期时间的数据格式字符串

asp.net - MVC3 Partial View 需要一个 Controller ,但我可以将其设为非公开吗?