While the ValidationMessageFor option is suitable in most cases i don't actually want a message next to the field. I use a ValidationSummary at the top of the page to list the errors. Adding a style attribute is also acceptable however i have several fields and i want to set the style on all of them to match and css would be the way i would expect to achieve this.
I've created a custom textboxfor which allows me to specify if the field is "locked" or "unlocked" I've made a few changes to make it add the validation class if there is a fault with the field while keeping any custom css classes.
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);
}