验证在DropDownList中选择所需 [英] Validating required selection in DropDownList

查看:78
本文介绍了验证在DropDownList中选择所需的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图模型定义了在显示为组合框属性。物业的定​​义是:

My view model defines property which has to be displayed as combo box. Property definition is:

[Required]
public int Processor { get; set; }

我用 DropDownListFor 渲染组合框:

<%=Html.DropDownListFor(r => r.Processor, Model.Processors, Model.Processor)%>

Model.Processors 包含的IEnumerable&LT; SelectListItem&GT; 定义为一个特殊的项目:

Model.Processors contains IEnumerable<SelectListItem> with one special item defined as:

var noSelection = new SelectListItem
  {
    Text = String.Empty,
    Value = "0"
  };

现在我需要验证添加到我的组合框以便用户必须选择不同的值,那么'NOSELECTION。我希望的一些配置 RequiredAttribute标签,但它并没有默认值设置。

Now I need to add validation to my combo box so that user must select different value then 'noSelection'. I hoped for some configuration of RequiredAttribute but it doesn't have default value setting.

推荐答案

这个怎么样:

[Required]
public int? Processor { get; set; }

和则:

<%= Html.DropDownListFor(
    x => x.Processor, Model.Processors, "-- select processor --"
) %>

而在你的POST操作

And in your POST action

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        // the model is valid => you can safely use model.Processor.Value here:
        int processor = model.Processor.Value;
        // TODO: do something with this value
    }
    ...
}

现在你不再需要手动添加 NOSELECTION 项。只要使用正确的 DropDownListFor 超载​​。

And now you no longer need to manually add the noSelection item. Just use the proper DropDownListFor overload.

这篇关于验证在DropDownList中选择所需的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆