Html Helper nasıl yazılır?

April 18, 2009 at 4:11 PMoozturk

Çok kolay yazılır. Bazı belirtilmesi gereken mecburi şeyler var onlara dikkat etmek gerekiyor o kadar. Nedir onlar?

- Bir class yaratmalısınız ve bu class static olmalı. Ayrıca eğer yazacağınız methodun Html class'ında görünmesini istiyorsanız class adınız Html olmalı ve partial olmalıdır. Yani:

     public static partial class Html

- Bu class içine yaratacağınız method'da aynı şekilde static olmalı, geriye string döndürmeli ve ilk değişkeni this htmlhelper helper olmalı (değişken adı size kalmış tabii). Bu arada HtmlHelper class'ı System.Web.Mvc namespace'i içinde bulunuyor. Yani:

     public static string Anchor(this HtmlHelper helper, string text, string link)

- Bu kadar.

 

Bir de örnek vereyim:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DenemeMVC
{
    public static partial class Html
    {
        public static string Anchor(this HtmlHelper helper, string text, string link)
        {
            var builder = new TagBuilder( "a" );
            builder.MergeAttribute( "href", link );

            return builder.ToString( TagRenderMode.StartTag ) + text + builder.ToString( TagRenderMode.EndTag );
        }
    }
}

 

Mesela yukarıdaki kodu kullanarak Html.Anchor("Microsoft", http://www.microsoft.com) diye kullanabilirsiniz ve ortaya bir anchor çıkacaktır.

Bu olay tamamen Anonymous methods'dur, başka da birşey değildir esasen.

 

Kolay gelsin.

Posted in: ASP.NET | MVC

Tags: ,

Comments (4) -

Thanks for sharing, I will bookmark and be back again

Reply

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

Reply

I will post a link to this page on my blog. I am sure my visitors will find that very useful.

Reply

Thank you for the entry. I just about passed your site up in

Reply

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading