Dot-Net
ASP.NET MVC 驗證組?
我有一個表單,我想根據按下的送出按鈕要求不同的欄位。範例:如果您按下送出按鈕 1,則需要欄位 A,但如果您按下送出按鈕 2,則只需要欄位 B。如果我仍在使用 Web 表單,我將為每個按鈕/驗證器組合分配不同的“驗證組”。 有沒有辦法在 MVC 中做到這一點,最好在模型上使用數據註釋? 我更願意用一個解決方案來實現客戶端和伺服器驗證,但我會盡我所能……
提前致謝!
啟用客戶端驗證的自定義驗證屬性怎麼樣(這樣您可以獲得客戶端和伺服器驗證)?下面的解決方案使用 jQuery 不顯眼的驗證。要使用它,您需要為所有按鈕指定特定名稱並將名稱傳遞給驗證屬性。該按鈕還需要具有某種類型的值,以便可以將其回發(因此伺服器端程式碼可以對其進行測試,即
<input type="submit" name="myButton" value="1" />)。我還沒有測試過這段程式碼,所以我不確定它是否開箱即用。您可能需要製作一些模組:模型的驗證屬性:
public class RequiredIfButtonClickedAttribute : ValidationAttribute, IClientValidatable { private RequiredAttribute _innerAttribute = new RequiredAttribute(); public string ButtonName { get; set; } public RequiredIfButtonClickedAttribute(string buttonName) { ButtonName = buttonName; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if ((value == null && !string.IsNullOrEmpty(HttpContext.Current.Request.Form[ButtonName]))) { if (!_innerAttribute.IsValid(value)) { return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName }); } } return ValidationResult.Success; } #region IClientValidatable Members public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule() { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "requiredifbuttonclicked" }; rule.ValidationParameters.Add("buttonname", ButtonName); yield return rule; } #endregion }客戶端腳本:
/// <reference path="jquery-1.4.4-vsdoc.js" /> /// <reference path="jquery.validate.unobtrusive.js" /> // When a button is clicked remove the clicked button class from all buttons and add it to the on that was clicked $(":submit").click(function () { $(":submit").removeClass('clickedButton'); $(this).addClass('clickedButton'); }); $.validator.addMethod('requiredifbuttonclicked', function (value, element, parameters) { // if the condition is true, reuse the existing // required field validator functionality if ($(".clickedButton").val("name") === parameters['buttonname']) return $.validator.methods.required.call( this, value, element, parameters); return true; } ); $.validator.unobtrusive.adapters.add( 'requiredifbuttonclicked', ['buttonname'], function (options) { options.rules['requiredifbuttonclicked'] = { buttonname: options.params['buttonname'] }; options.messages['requiredifbuttonclicked'] = options.message; });並像這樣使用它:
[RequiredIfButtonClicked("myButtonName")] public string Name { get; set; }