在 MVC3 中扩展不显眼的 javascript 以将样式添加到 div 客户端的最佳方法

发布于 2024-12-01 20:33:03 字数 2902 浏览 2 评论 0原文

我正在使用 html5/Razor/MVC3,利用 Twitter 的 Bootstrap 模板。我希望表单验证看起来像他们记录的那样光滑(http://twitter.github.com/bootstrap/#forms )。因此,如果我们看一下用于帐户注册的标准样板 MVC3,标记将如下所示:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class="form-stacked" })) {
    @Html.ValidationSummary(true, "Snap! Something went wrong")
    <div>
        <fieldset>
            <legend>Account Information</legend>
            <div class="clearfix error">
                @Html.LabelFor(m => m.UserName)
                <div class="input">
                    @Html.TextBoxFor(m => m.UserName)
                    <span class="help-inline">@Html.ValidationMessageFor(m => m.UserName)</span>
                </div>
            </div>

            <div class="clearfix">
                @Html.LabelFor(m => m.Email)
                <div class="input">
                    @Html.TextBoxFor(m => m.Email)
                    <span class="help-inline">@Html.ValidationMessageFor(m => m.Email)</span>
                </div>
            </div>

            <div class="clearfix">
                @Html.LabelFor(m => m.Password)
                <div class="input">
                    @Html.PasswordFor(m => m.Password)
                    <span class="help-inline">@Html.ValidationMessageFor(m => m.Password)</span>
                </div>
            </div>

            <div class="clearfix">
                @Html.LabelFor(m => m.ConfirmPassword)
                <div class="input">
                    @Html.PasswordFor(m => m.ConfirmPassword)
                    <span class="help-inline">@Html.ValidationMessageFor(m => m.ConfirmPassword)</span>
                </div>
            </div>
        </fieldset>
        <div class="actions">
            <button class="btn large primary" type="submit">Register</button>
        </div>
    </div>

我想要做的是让容器 div 注入“错误”类,就像我在第一个中硬编码的那样输入。 (因此,进入页面后,div 将具有“clearfix”类,但如果该输入块验证失败,它会将其标记为“clearfix 错误”)。我想我必须更新 div 块以包含某种 id,并且可能向 ValidationMessage 添加一个新的 data- 属性。我在扩展 ValidationMessageFor 帮助程序时没有问题。我只是不能 100% 确定扩展现有库的方法应该是什么。关于如何解决这个问题有什么建议吗?

TIA。

更新

我认为这种方法是合理的:

<div id="UserNameContainer" class="clearfix error">
    @Html.LabelFor(m => m.UserName)
    <div class="input">
        @Html.TextBoxFor(m => m.UserName)
        <span class="help-inline">@Html.ValidationMessageFor(m => m.UserName, null, new { @data_container = "UserNameContainer" })</span>
    </div>
</div>

通过用数据容器名称装饰我的验证消息,我就可以定位容器 div。现在我只需要弄清楚如何拦截验证消息。

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/bootstrap/#forms). So if we take a look at how the standard boiler-plate MVC3 for account registration, the markup would look like:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class="form-stacked" })) {
    @Html.ValidationSummary(true, "Snap! Something went wrong")
    <div>
        <fieldset>
            <legend>Account Information</legend>
            <div class="clearfix error">
                @Html.LabelFor(m => m.UserName)
                <div class="input">
                    @Html.TextBoxFor(m => m.UserName)
                    <span class="help-inline">@Html.ValidationMessageFor(m => m.UserName)</span>
                </div>
            </div>

            <div class="clearfix">
                @Html.LabelFor(m => m.Email)
                <div class="input">
                    @Html.TextBoxFor(m => m.Email)
                    <span class="help-inline">@Html.ValidationMessageFor(m => m.Email)</span>
                </div>
            </div>

            <div class="clearfix">
                @Html.LabelFor(m => m.Password)
                <div class="input">
                    @Html.PasswordFor(m => m.Password)
                    <span class="help-inline">@Html.ValidationMessageFor(m => m.Password)</span>
                </div>
            </div>

            <div class="clearfix">
                @Html.LabelFor(m => m.ConfirmPassword)
                <div class="input">
                    @Html.PasswordFor(m => m.ConfirmPassword)
                    <span class="help-inline">@Html.ValidationMessageFor(m => m.ConfirmPassword)</span>
                </div>
            </div>
        </fieldset>
        <div class="actions">
            <button class="btn large primary" type="submit">Register</button>
        </div>
    </div>

What I want to do is have the container div inject the "error" class like I've hard-coded in the first input. (So upon entering the page, the div would have a class of "clearfix" but if that input block failed validation, it would tag it as "clearfix error"). I figure I'm going to have to update the div block to include an id of some sort and perhaps add a new data- attribute to the ValidationMessage. I don't have a problem extending the ValidationMessageFor helper. I'm just not 100% sure what the approach should be for extending the library that's there. Any suggestions on how to approach this?

TIA.

UPDATE:

I am thinking this approach is reasonable:

<div id="UserNameContainer" class="clearfix error">
    @Html.LabelFor(m => m.UserName)
    <div class="input">
        @Html.TextBoxFor(m => m.UserName)
        <span class="help-inline">@Html.ValidationMessageFor(m => m.UserName, null, new { @data_container = "UserNameContainer" })</span>
    </div>
</div>

By decorating my validation message with a data-container name, I could then target the container div. Now I just need to figure out how to intercept the validation message.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

鱼忆七猫命九 2024-12-08 20:33:03

$.validator.setDefaults 方法通过 Twitter 的 Bootstrap 为我解决了这个问题。我正在使用jquery.validate.jsjquery.validate.unobtrusive.js

由于 DOM 就绪的非侵入式验证会扫描您的文档并为其遇到的每个表单缓存非侵入式验证选项,因此需要在文档扫描发生之前调用 $.validator.setDefaults 方法。

// 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
});

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
});
猫瑾少女 2024-12-08 20:33:03

遇到了同样的问题。我通过添加和扩展 HtmlHelper 类来解决这个问题。

这就是我对 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));

        }
    }

在 .cshtml 文件中,我将 Html.ValidationSummary 替换为:

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

请记住在视图文件夹 web.config 文件中添加扩展类的命名空间。

如果我先解决您之前的单个输入项目,我会稍后在这里发布。
华泰

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

枫林﹌晚霞¤ 2024-12-08 20:33:03

不要重新发明这个特定的轮子,而是检查

您可以根据需要自定义弹出元素,连接到 jQuery.validate.js 也很简单。

Rather than reinventing this particular wheel, check the validationEngine plugin available at http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/.

You can customize the popup elements as you want, and it is trivial to connect to jQuery.validate.js.

篱下浅笙歌 2024-12-08 20:33:03

我更喜欢更改 bootstrap 的 CSS。
刚刚在正确的位置添加了 jQuery 验证类。
字段验证错误和输入验证错误

    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;
}

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;
}
世态炎凉 2024-12-08 20:33:03

您可以通过将以下 javascript 添加到页面(视图)来将 MVC3 验证与 Bootstrap 框架集成。

<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>

此外,在视图(例如“Create.cshtml”)上,确保表单中的字段格式如下

    <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>

...对于这个解决方案,很可能只需添加 JavaScript 即可,无需编辑视图。

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.

夏の忆 2024-12-08 20:33:03

我所做的就是采用 css 类来处理验证错误,并创建一个具有相同类但具有引导值的新 css 文件。

您可以在 nuget 包中找到它: http://nuget.org/List/Packages /MahApps.Twitter.Bootstrap

它还提供了一些脚手架模板来自动创建新视图。

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.

眼眸 2024-12-08 20:33:03

我需要使用 Bootstrap 3.1 和 Razor 来解决这个问题。这就是我使用的:

$.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');
            }
        });
    });
});

这是@german的答案和帮助的组合 帖子,作者:“theBraindonor”。更新为使用新的 Bootstrap 3 类。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文