Best approach for extending unobtrusive javascript in MVC3 to add a style to a div client side

后端 未结 7 852
情话喂你
情话喂你 2021-01-31 03:50

I\'m using html5/Razor/MVC3 leveraging the Bootstrap template from Twitter. I want to have form validation that looks slick like they\'ve documented (http://twitter.github.com/b

相关标签:
7条回答
  • 2021-01-31 04:09

    The $.validator.setDefaults method solved this issue for me with Bootstrap from Twitter. I'm usingjquery.validate.js and jquery.validate.unobtrusive.js.

    Since unobtrusive validation on DOM ready scans your document and caches unobtrusive validation options for each form it encounters, it is needed to call the $.validator.setDefaults method before document scan occurs.

    // setup defaults for $.validator outside domReady handler
    $.validator.setDefaults({
        highlight: function (element) {
            $(element).closest(".clearfix").addClass("error");
        },
        unhighlight: function (element) {
            $(element).closest(".clearfix").removeClass("error");
        }
    });
    
    $(document).ready(function() {
           // do other stuff
    });
    
    0 讨论(0)
  • 2021-01-31 04:09

    You can integrate MVC3 validation with Bootstrap framework by adding the following javascript to your page (View)

    <script>
    $(document).ready(function () {
    /* Bootstrap Fix */
    $.validator.setDefaults({
        highlight: function (element) {
            $(element).closest("div.control-group").addClass("error");
        },
        unhighlight: function (element) {
            $(element).closest("div.control-group").removeClass("error");
        }
    });
    var current_div;
    $(".editor-label, .editor-field").each(function () {
        var $this = $(this);
        if ($this.hasClass("editor-label")) {
            current_div = $('<div class="control-group"></div>').insertBefore(this);
        }
        current_div.append(this);
    });
    $(".editor-label").each(function () {
        $(this).contents().unwrap();
    });
    $(".editor-field").each(function () {
        $(this).addClass("controls");
        $(this).removeClass("editor-field");
    });
    $("label").each(function () {
        $(this).addClass("control-label");
    });
    $("span.field-validation-valid, span.field-validation-error").each(function () {
        $(this).addClass("help-inline");
    });
    $("form").each(function () {
        $(this).addClass("form-horizontal");
        $(this).find("div.control-group").each(function () {
            if ($(this).find("span.field-validation-error").length > 0) {
                $(this).addClass("error");
            }
        });
    });
    });
    </script>
    

    Besides, on the Views (for example "Create.cshtml") make sure that the fields in the form are formatted as the following...

        <div class="editor-label">
            @Html.LabelFor(Function(model) model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(Function(model) model.Name)
            @Html.ValidationMessageFor(Function(model) model.Name)
        </div>
    

    With this solution, it will most likely be enough to just add a javascript without edit the View.

    0 讨论(0)
  • 2021-01-31 04:13

    I prefere to change the CSS of bootstrap. Just added the classes of jQuery validate in the right place. field-validation-error and input-validation-error

        form .clearfix.error > label, form .clearfix.error .help-block, form .clearfix.error .help-inline, .field-validation-error {
      color: #b94a48;
    }
    form .clearfix.error input, form .clearfix.error textarea, .input-validation-error {
      color: #b94a48;
      border-color: #ee5f5b;
    }
    form .clearfix.error input:focus, form .clearfix.error textarea:focus, .input-validation-error:focus {
      border-color: #e9322d;
      -webkit-box-shadow: 0 0 6px #f8b9b7;
      -moz-box-shadow: 0 0 6px #f8b9b7;
      box-shadow: 0 0 6px #f8b9b7;
    }
    
    0 讨论(0)
  • 2021-01-31 04:23

    Came accross the same issue. I am tackling it by adding and extesion to the HtmlHelper Class.

    This is what I did for the ValidationSummary:

       public static class TwitterBootstrapHelperExtensions
        {
            public static MvcHtmlString BootstrapValidationSummary(this HtmlHelper helper,
                                   bool excludePropertyErrors,
                                   string message)
            {
                if(helper.ViewData.ModelState.Values.All(v => v.Errors.Count == 0)) return new MvcHtmlString(string.Empty);
    
                string errorsList = "<ul>";
                foreach (var error in helper.ViewData.ModelState.Values.Where(v => v.Errors.Count >0))
                {
                    errorsList += string.Format("<li>{0}</li>", error.Errors.First().ErrorMessage);
                }
                errorsList += "</ul>";
                return new MvcHtmlString(string.Format("<div class=\"alert-message error\"><span>{0}</span>{1}</div>",message,errorsList));
    
            }
        }
    

    And in the .cshtml file I replace Html.ValidationSummary with this:

    @Html.BootstrapValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
    

    Remember to add the namespance of your extension class in the views folder web.config file.

    I will post here later if I tackle the individual input item before you. HTH

    0 讨论(0)
  • 2021-01-31 04:23

    What I've done is taken the css classes for the validation errors and created a new css file with the same classes but with bootstrap values.

    You can find it in a nuget package at: http://nuget.org/List/Packages/MahApps.Twitter.Bootstrap

    That also provides some scaffolding templates to autocreate new views.

    0 讨论(0)
  • 2021-01-31 04:23

    I needed to solve this using Bootstrap 3.1 and Razor. This is what I used:

    $.validator.setDefaults({
        highlight: function (element) {
            $(element).parents(".form-group").addClass("has-error");
        },
        unhighlight: function (element) {
            $(element).parents(".form-group").removeClass("has-error");
        }
    });
    
    $(function () {
    
        $('span.field-validation-valid, span.field-validation-error').each(function () {
            $(this).addClass('help-block');
        });
    
        $('form').submit(function () {
            if ($(this).valid()) {
                $(this).find('div.form-group').each(function () {
                    if ($(this).find('span.field-validation-error').length == 0) {
                        $(this).removeClass('has-error');
                    }
                });
            }
            else {
                $(this).find('div.form-group').each(function () {
                    if ($(this).find('span.field-validation-error').length > 0) {
                        $(this).addClass('has-error');
                    }
                });
            }
        });
    
        $('form').each(function () {
            $(this).find('div.form-group').each(function () {
                if ($(this).find('span.field-validation-error').length > 0) {
                    $(this).addClass('has-error');
                }
            });
        });
    });
    

    This is a combination of @german's answer and help from this post by "theBraindonor". Updated to use new Bootstrap 3 classes.

    0 讨论(0)
提交回复
热议问题