简体   繁体   English

如何在可以隐藏在mvc中的属性上使用必填属性

[英]how to use required attribute on properties that can be hidden in mvc

Scenario: The user should fill out a form and based on his choices different properties are displayed(using jquery .show and .hide). 场景:用户应该填写一个表单,并根据他的选择显示不同的属性(使用jquery .show和.hide)。 Problem: I want some of those properties that are shown to be required(but only when they are shown ofc). 问题:我希望某些显示的属性是必需的(但仅当它们显示为c时)。 The [Required] attribute doesn't care if the property is shown or not. [Required]属性不在乎该属性是否显示。 So if I use [Required] the user are asked to fill out properties he can't see. 因此,如果我使用[必需],则要求用户填写他看不见的属性。 Solution: ? 解决方案:

You could use the RequiredIf attribute to perform conditional validation: 您可以使用RequiredIf属性执行条件验证:

[RequiredIf("HiddenFoo", "true", ErrorMessage = "Foo is required")]
public string Foo { get; set; }

public string HiddenFoo { get; set; }

Now, add a hidden field called HiddenFoo and then toggle its value when you are showing/hiding the Foo textbox. 现在,添加一个名为HiddenFoo的隐藏字段,然后在显示/隐藏Foo文本框时切换其值。 Foo will be required only if HiddenFoo="true" . 仅当HiddenFoo="true"时才需要Foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM