twitter-bootstrap 在 MVC3 中扩展不显眼的 javascript 以向 div 客户端添加样式的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7215477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best approach for extending unobtrusive javascript in MVC3 to add a style to a div client side
提问by JBright
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:
我正在使用 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>
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?
我想要做的是让容器 div 注入“错误”类,就像我在第一个输入中硬编码一样。(因此,在进入页面时,div 将具有“clearfix”类,但如果该输入块未通过验证,则会将其标记为“clearfix 错误”)。我想我将不得不更新 div 块以包含某种类型的 id,并且可能会向 ValidationMessage 添加一个新的数据属性。我在扩展 ValidationMessageFor 助手时没有问题。我只是不是 100% 确定扩展现有库的方法应该是什么。关于如何解决这个问题的任何建议?
TIA.
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.
通过使用数据容器名称装饰我的验证消息,我可以定位容器 div。现在我只需要弄清楚如何拦截验证消息。
回答by Germán
The $.validator.setDefaultsmethod solved this issue for me with Bootstrap from Twitter. I'm usingjquery.validate.jsand jquery.validate.unobtrusive.js.
该$.validator.setDefaults方法使用 Twitter 的 Bootstrap 为我解决了这个问题。我正在使用jquery.validate.js和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.setDefaultsmethod before document scan occurs.
由于对 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
});
回答by Dimitris Maniatis
Came accross the same issue. I am tackling it by adding and extesion to the HtmlHelper Class.
遇到同样的问题。我正在通过向 HtmlHelper 类添加和扩展来解决它。
This is what I did for the ValidationSummary:
这是我为 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:
在 .cshtml 文件中,我将 Html.ValidationSummary 替换为:
@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.
请记住在视图文件夹 web.config 文件中添加扩展类的命名空间。
I will post here later if I tackle the individual input item before you. HTH
如果我在您之前处理单个输入项,我稍后会在这里发布。HTH
回答by Alberto Chvaicer
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
我更喜欢更改 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;
}
回答by Max
You can integrate MVC3 validation with Bootstrap framework by adding the following javascript to your page (View)
您可以通过将以下 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>
Besides, on the Views (for example "Create.cshtml") make sure that the fields in the form are formatted as the following...
此外,在视图(例如“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>
With this solution, it will most likely be enough to just add a javascript without edit the View.
使用此解决方案,很可能只需添加一个 javascript 而无需编辑视图。
回答by counsellorben
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/.
与其重新发明这个特定的轮子,不如检查http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/ 上提供的validationEngine 插件。
You can customize the popup elements as you want, and it is trivial to connect to jQuery.validate.js.
您可以根据需要自定义弹出元素,连接到 jQuery.validate.js 很简单。
回答by crucible
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.
我所做的是为验证错误采用 css 类,并创建一个具有相同类但具有引导值的新 css 文件。
You can find it in a nuget package at: http://nuget.org/List/Packages/MahApps.Twitter.Bootstrap
您可以在 nuget 包中找到它:http://nuget.org/List/Packages/MahApps.Twitter.Bootstrap
That also provides some scaffolding templates to autocreate new views.
这也提供了一些脚手架模板来自动创建新视图。
回答by shanabus
I needed to solve this using Bootstrap 3.1 and Razor. This is what I used:
我需要使用 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');
}
});
});
});
This is a combination of @german's answer and help from this postby "theBraindonor". Updated to use new Bootstrap 3 classes.
这是@german的回答和“theBraindonor”这篇文章的帮助的结合。更新为使用新的 Bootstrap 3 类。

