ASP .NET MVC Disable Client Side Validation at Per-Field Level

后端 未结 7 2069
梦毁少年i
梦毁少年i 2020-11-27 02:50

I\'m using ASP .NET MVC 3 with Data Annotations and the jQuery validate plugin.

Is there a way to mark that a certain field (or certain data annotation) should only

7条回答
  •  失恋的感觉
    2020-11-27 03:43

    I'm not sure if this solution works on MVC3. It surely works on MVC4:

    You can simply disable client side validation in the Razor view prior to render the field and re-enable client side validation after the field has been rendered.

    Example:

    @{ Html.EnableClientValidation(false); } @Html.TextBoxFor(m => m.BatchId, new { @class = "k-textbox" }) @{ Html.EnableClientValidation(true); }

    Here we disable client side validation for the BatchId field.

    Also I have developed a little helper for this:

    public static class YnnovaHtmlHelper
    {
        public static ClientSideValidationDisabler BeginDisableClientSideValidation(this HtmlHelper html)
        {
            return new ClientSideValidationDisabler(html);
        }
    }
    
    public class ClientSideValidationDisabler : IDisposable
    {
        private HtmlHelper _html;
    
        public ClientSideValidationDisabler(HtmlHelper html)
        {
            _html = html;
            _html.EnableClientValidation(false);
        }
    
        public void Dispose()
        {
            _html.EnableClientValidation(true);
            _html = null;
        }
    }
    

    You will use it as follow:

    @using (Html.BeginDisableClientSideValidation()) { @Html.TextBoxFor(m => m.BatchId, new { @class = "k-textbox" }) }

    If anyone has better solutions please let me know!

    Hope this help.

提交回复
热议问题