cómo crear un HTML Helper para extender TextBoxFor() para agregar estilo CSS?cómo crear un HTML Helper para extender TextBoxFor() para agregar estilo CSS?
@Html.TextBoxFor(model => model.FirstName, new { @class = "txt" })
cómo crear un HTML Helper para extender TextBoxFor() para agregar estilo CSS?cómo crear un HTML Helper para extender TextBoxFor() para agregar estilo CSS?
@Html.TextBoxFor(model => model.FirstName, new { @class = "txt" })
public static System.Web.Mvc.MvcHtmlString DtxTextBoxFor<TModel, TValue>
(this System.Web.Mvc.HtmlHelper<TModel> html,
System.Linq.Expressions.Expression<System.Func<TModel, TValue>> expression,
System.Collections.Generic.IDictionary<string, object> htmlAttributes = null, bool readOnly = false)
{
if (htmlAttributes == null)
{
htmlAttributes =
new System.Collections.Generic.Dictionary<string, object>();
}
System.Web.Mvc.ModelMetadata oModelMetadata =
System.Web.Mvc.ModelMetadata.FromLambdaExpression(expression, html.ViewData);
if (oModelMetadata == null)
{
if (readOnly)
{
if (htmlAttributes.ContainsKey("readonly") == false)
{
htmlAttributes.Add("readonly", "read-only");
}
}
}
else
{
if (htmlAttributes.ContainsKey("placeholder") == false)
{
string strHtmlFieldName =
System.Web.Mvc.ExpressionHelper.GetExpressionText(expression);
string strLabelText =
oModelMetadata.DisplayName ??
oModelMetadata.PropertyName ??
strHtmlFieldName.Split('.').Last();
if (string.IsNullOrEmpty(strLabelText) == false)
{
htmlAttributes.Add("placeholder", strLabelText);
}
}
if ((readOnly) || (oModelMetadata.IsReadOnly))
{
if (htmlAttributes.ContainsKey("readonly") == false)
{
htmlAttributes.Add("readonly", "read-only");
}
}
}
htmlAttributes.Add("class", "form-control");
System.Linq.Expressions.MemberExpression oMemberExpression =
expression.Body as System.Linq.Expressions.MemberExpression;
if (oMemberExpression != null)
{
System.ComponentModel.DataAnnotations.StringLengthAttribute oStringLengthAttribute =
oMemberExpression.Member.GetCustomAttributes
(typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), false)
.FirstOrDefault() as System.ComponentModel.DataAnnotations.StringLengthAttribute;
if (oStringLengthAttribute != null)
{
if (htmlAttributes.ContainsKey("maxlength") == false)
{
htmlAttributes.Add("maxlength", oStringLengthAttribute.MaximumLength);
}
}
}
return (html.TextBoxFor(expression, htmlAttributes));
}
sólo tiene que crear un extension method en HtmlHelper
:
public static class MyHtmlHelpers
{
public static MvcHtmlString MyTextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
return helper.TextBoxFor(expression, new { @class = "txt" });
}
}
A continuación, en su opinión, se puede utilizar como:
@Html.MyTextBoxFor(model => model.FirstName)
Nota: No se olvide de la @using
espacio de nombres de MyHtmlHelpers
si sus puntos de vista.
bueno ... gracias por la solución, solo quería saber si puedo hacer que el nombre de la extensión sea el mismo, significa en lugar de MyTextBoxFor , ¿Puedo mantener el mismo nombre que TextForFor? – user584018
Puede tener un método de extensión con el mismo nombre, p. 'TextBoxFor', el problema es que el espacio de nombres del built-in 'TextBoxFor' está incluido por defecto. Entonces, para utilizar su método de extensión, necesita llamar a través de la clase estática 'MyHtmlHelpers.TextBoxFor (Html, model => model.FirstName)' de lo contrario, el compilador no puede eliminar la ambigüedad. Puede eliminar el espacio de nombre predeterminado incluido, pero llamar a los ayudantes integrados será problemático. – nemesv
cómo aceptar htmlAttrbutes en la entrada de nuestro HtmlHelper y agregar esta clase a ellos? @nemesv – MRebati
Basándose en @nemesv answer here es una extensión que admite htmlAttributes con atributos personalizados adicionales.
vb.net:
<Extension()>
Function MyTextBoxFor(Of TModel, TProperty)(ByVal helper As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of TModel, TProperty)), htmlAttributes As Object) As MvcHtmlString
'copy htmlAttributes object to Dictionary
Dim dicHtmlAttributes As New Dictionary(Of String, Object)
For Each prop in htmlAttributes.GetType().GetProperties()
dicHtmlAttributes.Add(prop.Name,prop.GetValue(htmlAttributes))
Next
'add custom attribute
dicHtmlAttributes.Add("foo","bar")
Return helper.TextBoxFor(expression, dicHtmlAttributes)
End Function
C#:
public static MvcHtmlString MyTextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
//copy htmlAttributes object to Dictionary
Dictionary<string, object> dicHtmlAttributes = new Dictionary<string, object>;
foreach (var prop in htmlAttributes.GetType().GetProperties())
{
dicHtmlAttributes.Add(prop.Name, prop.GetValue(htmlAttributes));
}
//add custom attribute
dicHtmlAttributes.Add("foo", "bar");
return helper.TextBoxFor(expression, dicHtmlAttributes);
}
posible duplicado de [ASP.NET MVC - Ampliación TextBoxFor sin volver a escribir el método] (http://stackoverflow.com/ preguntas/6202053/asp-net-mvc-extends-textboxfor-without-re-writing-the-method) –