我有一个用于控制剃刀视图的文本框:
@Html.TextBoxFor(model => model.PrimaryAddressLine1)
如果用户将此字段留空,则验证将添加class =" input-validation-error"到现场将其颜色改为红色(如预期的那样)。但是,如果我尝试将自定义css类添加到字段中,如下所示:
@Html.TextBoxFor(model => model.PrimaryAddressLine1, new { @Class = "addressfield" })
我将红色松散为"输入验证错误" class不再添加到控件中。
如何保持红色并添加我的自定义CSS类?
答案 0 :(得分:2)
将@Class更改为@class。这对我有用。
@Html.TextBoxFor(model => model.PrimaryAddressLine1, new { @class = "addressfield" })
答案 1 :(得分:1)
在文本框行下面添加验证器,如下所示
<div class="form-group">
@Html.LabelFor(c => c.CompanyName, new { @class = "col-md-2 control-label" })
<div class="col-sm-10 ">
@Html.TextBoxFor(c=>c.CompanyName, new { @class = "form-control" })
@Html.ValidationMessageFor(c => c.CompanyName, "", new { @style="color:blue;"})
</div>
</div>
输出将是这样的
答案 2 :(得分:1)
虽然ValidationMessageFor选项在大多数情况下都适用,但实际上并不想在该字段旁边显示消息。我在页面顶部使用ValidationSummary列出错误。添加样式属性也是可以接受的,但我有几个字段,我想在所有字段上设置匹配的样式,而css将是我期望实现的方式。
我已经创建了一个自定义文本框,允许我指定该字段是否已锁定&#34;或者&#34;解锁&#34;我做了一些更改,如果在保留任何自定义css类的同时字段出现故障,则添加验证类。
public static MvcHtmlString LockableTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool locked)
{
string fullName = ExpressionHelper.GetExpressionText(expression);
// Convert htmlAttributes into a dictionary
RouteValueDictionary dic = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
// Get the validation attributes
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
IDictionary<string, object> validationAttributes = helper
.GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);
// Merge attributes
foreach (var item in validationAttributes)
{
if (dic.ContainsKey(Key))
dic[Key] = string.Format("{0} {1}", dic[Key], Value);
else
dic.Add(Key, Value);
}
// If there are any errors for a named field, we add the CSS attribute.
ModelState modelState;
if (helper.ViewData.ModelState.TryGetValue(fullName, out modelState) && modelState.Errors.Count > 0)
dic.HikiAddUpdateItem("class", HtmlHelper.ValidationInputCssClassName);
// Toggle readonly
if (locked)
{
if (dic.ContainsKey("readonly"))
dic["readonly"] = "readonly"
else
dic.Add("readonly", "readonly");
}
// Return textbox
return helper.TextBoxFor(expression, dic);
}
答案 3 :(得分:0)
试试这个:
@Html.TextBoxFor(model => model.PrimaryAddressLine1, new { @id = "oid", @class= "addressfield" })
<span style="color: Red">@Html.ValidationMessageFor(model => model.PrimaryAddressLine1)</span>