CSS 将 Twitter Bootstrap 验证样式和消息应用于 ASP.NET MVC 验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11468130/
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
Apply Twitter Bootstrap Validation Style and Message to ASP.NET MVC validation
提问by SiberianGuy
How can I integrate ASP.NET MVC unobtrusive validation and Twitter Bootstrap? I want to have all those validation messagesand stylesappropriately.
如何集成 ASP.NET MVC 非侵入式验证和 Twitter Bootstrap?我想适当地拥有所有这些验证消息和样式。
采纳答案by Shaddix
I suggest to include Bootstrapper in less format and do the same thing as Iridio suggested but in .less. That way you could have something like:
我建议以较少的格式包含 Bootstrapper,并执行与 Iridio 建议的相同但在 .less 中的操作。这样你就可以有类似的东西:
.validation-summary-errors
{
.alert();
.alert-error();
}
.field-validation-error
{
.label();
.label-important();
}
so when bootstrapper will change you'll pick up the changes automatically.
Regular styles that handle visibility from MVC default Site.css
will stay in place and handle visibility.
所以当引导程序发生变化时,您将自动获取更改。处理 MVC 默认可见性的常规样式Site.css
将保持原位并处理可见性。
回答by Leniel Maccaferri
A nice way of handling this if you're using Bootstrap 2 is...
如果您使用 Bootstrap 2,一个很好的处理方法是......
Add this to your _Layout.cshtml
:
将此添加到您的_Layout.cshtml
:
<script type="text/javascript">
jQuery.validator.setDefaults({
highlight: function (element, errorClass, validClass) {
if (element.type === 'radio') {
this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else {
$(element).addClass(errorClass).removeClass(validClass);
$(element).closest('.control-group').removeClass('success').addClass('error');
}
},
unhighlight: function (element, errorClass, validClass) {
if (element.type === 'radio') {
this.findByName(element.name).removeClass(errorClass).addClass(validClass);
} else {
$(element).removeClass(errorClass).addClass(validClass);
$(element).closest('.control-group').removeClass('error').addClass('success');
}
}
});
$(function () {
$("span.field-validation-valid, span.field-validation-error").addClass('help-inline');
$("div.control-group").has("span.field-validation-error").addClass('error');
$("div.validation-summary-errors").has("li:visible").addClass("alert alert-block alert-error");
});
</script>
These are the posts where I found the code pieces above:
这些是我在上面找到代码片段的帖子:
Integrating Bootstrap Error styling with MVC's Unobtrusive Error Validation
将 Bootstrap 错误样式与 MVC 的不显眼的错误验证相结合
Twitter Bootstrap validation styles with ASP.NET MVC
使用 ASP.NET MVC 的 Twitter Bootstrap 验证样式
MVC Twitter Bootstrap unobtrusive error handling
MVC Twitter Bootstrap 不显眼的错误处理
UPDATE
更新
Right now I needed to do the same when using Bootstrap 3. Here's the modifications necessary since the class names changed:
现在我需要在使用Bootstrap 3时做同样的事情。以下是类名更改后所需的修改:
<script type="text/javascript">
jQuery.validator.setDefaults({
highlight: function (element, errorClass, validClass)
{
if (element.type === 'radio')
{
this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else
{
$(element).addClass(errorClass).removeClass(validClass);
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
}
},
unhighlight: function (element, errorClass, validClass)
{
if (element.type === 'radio')
{
this.findByName(element.name).removeClass(errorClass).addClass(validClass);
} else
{
$(element).removeClass(errorClass).addClass(validClass);
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
}
}
});
$(function () {
$("span.field-validation-valid, span.field-validation-error").addClass('help-block');
$("div.form-group").has("span.field-validation-error").addClass('has-error');
$("div.validation-summary-errors").has("li:visible").addClass("alert alert-block alert-danger");
});
</script>
回答by Iridio
Copy the css of the validators in your css file and change the color accordinlgly. Something like this should do
复制 css 文件中验证器的 css 并相应地更改颜色。这样的事情应该做
.field-validation-error {
color: #b94a48;
display: inline-block;
*display: inline;
padding-left: 5px;
vertical-align: middle;
*zoom: 1;
}
.field-validation-valid {
display: none;
}
.input-validation-error {
/*
border: 1px solid #ff0000;
background-color: #ffeeee;
*/
color: #b94a48;
border-color: #b94a48;
}
.input-validation-error:focus {
border-color: #953b39;
-webkit-box-shadow: 0 0 6px #d59392;
-moz-box-shadow: 0 0 6px #d59392;
box-shadow: 0 0 6px #d59392;
}
.validation-summary-errors {
/*font-weight: bold;*/
color: #b94a48;
}
.validation-summary-valid {
display: none;
}
回答by meffect
Why not just use css !important and call it a day:
为什么不直接使用 css !important 并收工:
/* Styles for validation helpers
-----------------------------------------------------------*/
.field-validation-error {
color: #f00 !important;
}
.field-validation-valid {
display: none;
}
.input-validation-error {
border: 1px solid #f00 !important;
background-color: #fee !important;
}
.validation-summary-errors {
font-weight: bold;
color: #f00;
}
.validation-summary-valid {
display: none;
}
回答by Roman Pushkin
On Bootstrap 3you have to add:
在 Bootstrap 3 上,您必须添加:
.validation-summary-errors
{
.alert();
.alert-danger();
}
.field-validation-error
{
.label();
.label-danger();
}
you'll see something like that:
你会看到类似的东西:
回答by Richard Ev
For the ValidationSummary
, you can use the overload that allows you to specify htmlAttributes
. This allows you to set it to use the Twitter Bootstrap alert css styles.
对于ValidationSummary
,您可以使用允许您指定的重载htmlAttributes
。这允许您将其设置为使用 Twitter Bootstrap 警报 css 样式。
@Html.ValidationSummary(string.Empty, new { @class = "alert alert-danger" })
A similar overload exists for the ValidationMessage
and ValidationMessageFor
helper methods.
ValidationMessage
和ValidationMessageFor
辅助方法存在类似的重载。
回答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>
回答by Ben Ripley
For those using Bootstrap 3, the css classes have changed and the solutions above need modifications to work with Bootstrap 3. I have used the following with success with MVC 4 and Bootstrap 3. See thisSO thread for more:
对于那些使用 Bootstrap 3 的人,css 类已经改变,上面的解决方案需要修改才能与 Bootstrap 3 一起使用。我在 MVC 4 和 Bootstrap 3 中成功使用了以下内容。有关更多信息,请参阅此SO 线程:
$(function () {
// any validation summary items should be encapsulated by a class alert and alert-danger
$('.validation-summary-errors').each(function () {
$(this).addClass('alert');
$(this).addClass('alert-danger');
});
// update validation fields on submission of form
$('form').submit(function () {
if ($(this).valid()) {
$(this).find('div.control-group').each(function () {
if ($(this).find('span.field-validation-error').length == 0) {
$(this).removeClass('has-error');
$(this).addClass('has-success');
}
});
}
else {
$(this).find('div.control-group').each(function () {
if ($(this).find('span.field-validation-error').length > 0) {
$(this).removeClass('has-success');
$(this).addClass('has-error');
}
});
$('.validation-summary-errors').each(function () {
if ($(this).hasClass('alert-danger') == false) {
$(this).addClass('alert');
$(this).addClass('alert-danger');
}
});
}
});
// check each form-group for errors on ready
$('form').each(function () {
$(this).find('div.form-group').each(function () {
if ($(this).find('span.field-validation-error').length > 0) {
$(this).addClass('has-error');
}
});
});
});
var page = function () {
//Update the validator
$.validator.setDefaults({
highlight: function (element) {
$(element).closest(".form-group").addClass("has-error");
$(element).closest(".form-group").removeClass("has-success");
},
unhighlight: function (element) {
$(element).closest(".form-group").removeClass("has-error");
$(element).closest(".form-group").addClass("has-success");
}
});
}();
回答by Darren Fang
You can add a few classes to your Site.css file:
您可以向 Site.css 文件中添加一些类:
/* styles for validation helpers */
.field-validation-error {
color: #b94a48;
}
.field-validation-valid {
display: none;
}
input.input-validation-error {
border: 1px solid #b94a48;
}
select.input-validation-error {
border: 1px solid #b94a48;
}
input[type="checkbox"].input-validation-error {
border: 0 none;
}
.validation-summary-errors {
color: #b94a48;
}
.validation-summary-valid {
display: none;
}
FYI: http://weblogs.asp.net/jdanforth/form-validation-formatting-in-asp-net-mvc-5-and-bootstrap-3
仅供参考:http: //weblogs.asp.net/jdanforth/form-validation-formatting-in-asp-net-mvc-5-and-bootstrap-3
回答by Donal
This is a neat solution that gives you more control over how the ValidationSummary renders errors to the view. The Unordered List it produced did not look right inside the alert. Therefore, I simply looped through the errors and rendered them how I wanted - using paragraphs in this case. For example:
这是一个巧妙的解决方案,可让您更好地控制 ValidationSummary 如何将错误呈现给视图。它生成的无序列表在警报中看起来并不正确。因此,我只是简单地遍历错误并按照我想要的方式呈现它们 - 在这种情况下使用段落。例如:
@if (ViewData.ModelState.Any(x => x.Value.Errors.Any()))
{
<div class="alert alert-danger" role="alert">
<a class="close" data-dismiss="alert">×</a>
@foreach (var modelError in Html.ViewData.ModelState.SelectMany(keyValuePair => keyValuePair.Value.Errors))
{
<p>@modelError.ErrorMessage</p>
}
</div>
}