asp.net-mvc 验证 DropDownList 中所需的选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4672289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:42:33  来源:igfitidea点击:

Validating required selection in DropDownList

asp.net-mvcasp.net-mvc-2validation

提问by Ladislav Mrnka

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

我的视图模型定义了必须显示为组合框的属性。属性定义是:

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

I'm using DropDownListForto render combo box:

DropDownListFor用来渲染组合框:

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

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

Model.Processors包含IEnumerable<SelectListItem>一个特殊项目,定义为:

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

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 RequiredAttributebut it doesn't have default value setting.

现在我需要向我的组合框添加验证,以便用户必须选择不同的值,然后是“noSelection”。我希望有一些配置,RequiredAttribute但它没有默认值设置。

回答by Darin Dimitrov

How about this:

这个怎么样:

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

And then:

进而:

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

And in your POST action

并在您的 POST 操作中

[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
    }
    ...
}

And now you no longer need to manually add the noSelectionitem. Just use the proper DropDownListForoverload.

现在您不再需要手动添加noSelection项目。只需使用正确的DropDownListFor重载即可。

回答by KyleMit

One possible issue is that jQuery Validate does run any rules if the value of an element is empty.

一个可能的问题是,如果元素的值为空,则 jQuery Validate 确实会运行任何规则

You can get around this by retriggering the validationwhen the user loses focus:

您可以通过在用户失去焦点时重新触发验证来解决此问题:

// select statements not firing null validation automatically
$("select").blur(function () { $(this).valid() });