4

Estou tentando escrever um HtmlHelper e vendo alguns exemplos básicos achei um com a classe TagBuilder que já ajuda:

namespace MyNamespace 
{  
    public static class MyHeleprs
    { 
        public static MvcHtmlString Image(this HtmlHelper htmlHelper, 
        string source, string alternativeText)
        {
            //declare the html helper 
            var builder = new TagBuilder("image"); 
            //hook the properties and add any required logic
            builder.MergeAttribute("src", source);
            builder.MergeAttribute("alt", alternativeText);
            //create the helper with a self closing capability
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        } 
    } 
}

Só que eu desejo criar um facilitador maior, para no fim manipular um valor que vai ser exibido, algumas classes css etc. Logo, não gostaria de ter que reescrever todo um helper que já existe como o TextBoxFor ou o EditorFor.

Partindo dessa vontade, então pensei em poder reaproveitar esses helpers e adicionar minhas manipulações.

Estava pensando em fazer o seguinte:

public static MvcHtmlString FieldFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    string cssClass = "",
    bool placeHolder = false,
    bool autoFocus = false,
    object htmlAttributes = null)
{
    var builder = new TagBuilder(
        htmlHelper.TextBoxFor(expression, htmlAttributes).ToString());

    // value attribute
    ...
    builder.Attributes["type"] = "text";
    builder.Attributes["value"] = value;           

    // autofocus
    if (autoFocus)
        builder.Attributes.Add("autofocus", "autofocus");

    // css
    builder.AddCssClass(cssClass);

    // placeholder
    ...
    return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
}

Enfim, destacando o que eu pensei:

var builder = new TagBuilder(htmlHelper.TextBoxFor(expression, htmlAttributes).ToString());

Mas o TagBuilder não funciona assim.

Manipular algo já pronto ajuda por não ter que ficar reescrevendo coisas que o framework já faz, como gerar a Id e o Name do elemento entre outros.

Como posso resolver isso? Qual seria um caminho mais prático?

1 Resposta 1

5

Exemplo:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace System.Web.Mvc
{
    public static class Methods
    {
        public static String ControllerName(this HtmlHelper HtmlHelper)
        {
            return HtmlHelper.ViewContext.RequestContext.RouteData.Values["controller"].ToString();
        }
        public static String ControllerName(this AjaxHelper AjaxHelper)
        {
            return AjaxHelper.ViewContext.RequestContext.RouteData.Values["controller"].ToString();
        }
        public static String ActionName(this HtmlHelper HtmlHelper)
        {
            return HtmlHelper.ViewContext.RequestContext.RouteData.Values["action"].ToString();
        }
        public static String ActionName(this AjaxHelper AjaxHelper)
        {
            return AjaxHelper.ViewContext.RequestContext.RouteData.Values["action"].ToString();
        }
        public static IHtmlString FieldFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression,
            string cssClass = "",
            string placeHolder = "",
            bool autoFocus = false,
            object htmlAttributes = null)
        {
            IDictionary<string, object> htmlAttributesList = new Dictionary<string, object>();
            if (htmlAttributes != null)
            {
                foreach (PropertyInfo prop in htmlAttributes.GetType().GetProperties())
                {
                    htmlAttributesList.Add(prop.Name, prop.GetValue(htmlAttributes));
                }
            }            
            if (!String.IsNullOrEmpty(cssClass))
            {
                htmlAttributesList.Add("css", cssClass);
            }
            if (!String.IsNullOrEmpty(placeHolder))
            {
                htmlAttributesList.Add("placeholder", placeHolder);
            }
            if (autoFocus)
            {
                htmlAttributesList.Add("autofocus", "autofocus");
            }            
            return new MvcHtmlString(htmlHelper.TextBoxFor(expression, htmlAttributesList).ToHtmlString());
        }      
    }
}

Obs: Existem além do que você tinha alguns métodos a mais que geralmente eu uso para montar alguma coisa padrão, mas, a sua dúvida seria assim a maneira de se fazer, sem a TagBuilder.

Como usar:

@Html.FieldFor(a => a.Nome);
@Html.FieldFor(a => a.Nome, htmlAttributes: new { id="Nome" })
@Html.FieldFor(a => a.Nome, cssClass: "", placeHolder: "", autoFocus: false, htmlAttributes: null)
@Html.FieldFor(a => a.Nome, "form-control", "Digite o seu nome", true, null)
1
  • 1
    Só lembrando que esse código ta testado e funcionou pelo menos nos meus testes não sei se passou algo qualquer coisa mantenha informado... vlw @TiagoSilva
    – user6026
    2/07/2014 às 22:26

Você deve fazer log-in para responder a esta pergunta.