4 de julho de 2011

Asp.Net - MVC 3 Html Helpers

Usando: VS2010, Asp.net Mvc 3.0 e C#


1 - Crie um novo projeto File | New | Project | Web | Asp.net Mvc 3 Web Application 
2 - De nome MyHtmlHelper 

























 3 - Crie um novo Folder: Helpers























4 - Crie um nova Classe no folder Helpers chamada : HtmlHelpers.cs


5 - Adicione o código abaixo :


using System.Web.Mvc;

namespace MyHtmlHelper.Helpers
{
    public static class HtmlHelpers
    {
        public static string Truncate(this HtmlHelper helper, string input, int length)
        {
            if (input.Length <= length)
            {
                return input;
            }
            else
            {
                return input.Substring(0, length) + "...";
            }
        }
    }
}

6 - Vamos adicionar a referencia no web.config para que todas as paginas desse projeto possa ter acesso.


    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
        <add namespace="MyHtmlHelper.Helpers" />
      </namespaces>
    </pages>



7 - Abra abra a Views | Home | index.aspx do seu projeto e modifique o codigo abaixo :


<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: Html.Truncate((string)ViewBag.Message,10) %></h2>
    <p>
        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
    </p>
</asp:Content>

8 - O resultado, foi criado um html helper no qual trunca sua string.

Nenhum comentário:

Postar um comentário