【问题标题】:How can I invalidate or stop processing of the form from inside a submit button click event handler?如何使提交按钮单击事件处理程序中的表单无效或停止处理?
【发布时间】:2023-12-16 19:50:01
【问题描述】:

我正在尝试为在 Kentico v10.0.51 和 .NET Framework 4.6 上运行的自定义表单控件实现一些自定义服务器端验证逻辑。我希望这个逻辑在提交事件上运行,并且我想在自定义表单控件的代码隐藏中定义逻辑。如何使提交按钮单击事件处理程序中的表单无效或停止处理?例如,请参阅附件中的简化测试用例。

https://pastebin.com/Lnt0Rn9y

using System;
using CMS.FormEngine.Web.UI;
using CMS.Helpers;
// ReSharper disable ArrangeAccessorOwnerBody

namespace CMSApp.CMSFormControls.Custom
{
    public partial class ServerSideValidator : FormEngineUserControl
    {
        public override object Value
        {
            get { return txtValue.Value; }
            set { txtValue.Value = ValidationHelper.GetString(value, string.Empty); }
        }

        protected override void OnInit(EventArgs e)
        {
            Form.SubmitButton.Click += SubmitButtonOnClick;
            base.OnInit(e);
        }

        private void SubmitButtonOnClick(object sender, EventArgs e)
        {
            var valid = CustomValidationHelper.ServerSideValidationMethod(Value);

            if (!valid)
            {
                //TODO: Invalidate the form before save or notify. (Form.?)
            }
        }
    }
}

【问题讨论】:

    标签: c# asp.net forms validation kentico


    【解决方案1】:

    使用被覆盖的方法:

    /// <summary>
    /// Returns true if a color is selected. Otherwise, it returns false and displays an error message.
    /// </summary>
    public override bool IsValid()
    {
         if ((string)Value != "")
         {
             return true;
         }
         else
         {
             // Sets the form control validation error message
             this.ValidationError = "Please choose a color.";
             return false;
         }
    }
    

    else 语句中,对您要验证的字段或表达式执行验证,并根据您正在验证的内容返回一条消息。

    【讨论】: