HTML Helper Class چیست
کمکهای HTML راهی هستند که میتوانیم html را در صفحه نمایش MVC ارائه کنیم. این Helpers توابع سادهای هستند که به توسعهدهنده اجازه میدهند نوع HTML مورد نیاز در نما را مشخص کند.
Helpers داخلی زیر در دسترس هستند.
- Html.ActionLink
- Html.BeginForm
- Html.CheckBox
- Html.DropDownList
- Html.EndForm
- Html.Hidden
- Html.ListBox
- Html.Password
- Html.RadioButton
- Html.TextArea
- Html.TextBox
برخی از Html Helper نیز برای نمایش با تایپ قوی موجود است.
- Html.CheckBoxFor
- Html.DropDownListFor
- Html.HiddenFor
- Html.ListBoxFor
- Html.PasswordFor
- Html.RadioButtonFor
- Html.TextAreaFor
- Html.TextBoxFor
لیست بالا از HTML Helper برای نمای قوی تایپ شده است. در داخل این متدهای کمکی، عبارت lambda را به عنوان آرگومان متد ارسال می کنیم.
اما اگر بخواهیم متد HTML Helper خودمان را ایجاد کنیم، سه راه برای ایجاد Html Helper سفارشی وجود دارد.
- با استفاده از روش استاتیک
- با استفاده از روش Extension
- با استفاده از @helper
راهنمای سفارشی با استفاده از روش استاتیک
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace CustomHelper.CustomHelpers
- {
- /// <summary>
- /// This Class Helpes
- /// </summary>
- public static class HelperByStaticMethod
- {
- /// <summary>
- /// This is a Helper Method For Image Element
- /// </summary>
- /// <param name="Source">Provide Source</param>
- /// <param name="Alt">alt Attribute For That Image</param>
- /// <param name="Title">Title For the Image</param>
- /// <param name="Height">Height Attribute (By Default Height will be 128)</param>
- /// <param name="Width">Width Attribute (By Default Width will be 128)</param>
- /// <returns></returns>
- public static string img(string Source, string Alt, string Title, int Height=128, int Width=128)
- {
- return String.Format("<img src='{0}' alt='{1}' title='{2}' height='{3}' width='{4}'/>", Source, Alt, Title, Height, Width);
- }
- }
- }
و در داخل View ما مانند زیر استفاده خواهیم کرد:
- @using CustomHelper.CustomHelpers
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- </head>
- <body>
- <div>
- @Html.Raw(HelperByStaticMethod.img("/Images/1.jpg", "Mark Zuck", "Mark Zuckerberg"))
- @Html.Raw(HelperByStaticMethod.img("/Images/2.jpg", "Bill Gates", "Bill Gates", 250, 167))
- @Html.Raw(HelperByStaticMethod.img("/Images/3.jpg", "APJ Abdul Kalam", "APJ Abdul Kalam", 250))
- @Html.Raw(HelperByStaticMethod.img("/Images/4.jpg", "Steve Jobs", "Steve Jobs", 200, 200))
- </div>
- </body>
- </html>
خروجی
در کد بالا یک کلاس و متد استاتیک ایجاد کردهام که Image Source، Alt، Title، Height و Width را میگیرد و رشته ساده را برمیگرداند. اما یک مشکل این است که من به صراحت اینها را با استفاده از Html.Raw به فرمت html تبدیل می کنم. اگر این رشته را به فرمت html تبدیل نکنم و کد خود را مانند زیر نگه دارم،