The goal of this tutorial is to demonstrate how you can create custom HTML Helpers     that you can use within your MVC views. By taking advantage of HTML Helpers, you can reduce the amount of tedious typing of HTML tags that you must perform to create a standard HTML page.
  In the first part of this tutorial, I describe some of the existing HTML Helpers included with the ASP.NET MVC framework. Next, I describe two methods of creating custom HTML Helpers: I explain how to create custom HTML Helpers by creating a static method and by creating an extension method.

  Understanding HTML Helpers

  An HTML Helper is just a method that returns a string. The string can represent     any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input> and <img> tags. You also can use HTML Helpers to render more complex content such as a tab strip or an HTML table of database data.

  The ASP.NET MVC framework includes the following set of standard HTML Helpers (this  is not a complete list):

  • Html.ActionLink()
  • Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()

  For example, consider the form in Listing 1. This form is rendered with the help of two of the standard HTML Helpers (see Figure 1). This form uses the Html.BeginForm() and Html.TextBox() Helper methods to render a simple HTML form.

Listing 1 – Views\Home\Index.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns= "http://www.w3.org/1999/xhtml ">
<head id="Head1" runat="server">
<title>Index</title>
</head>
<body>
<div>
<% using (Html.BeginForm())
{ %> <label for="firstName">First Name:</label>
<br />
<%= Html.TextBox("firstName")%>
<br /><br />
<label for="lastName">Last Name:</label>
<br /> <%= Html.TextBox("lastName")%>
<br /><br />
<input type="submit" value="Register" />
<% } %>
</div>
</body>
</html>

  The Html.BeginForm() Helper method is used to create the opening and closing HTML <form> tags. Notice that the Html.BeginForm() method is called within a using statement. The using statement ensures that the <form> tag gets closed at the end of the using block.

  If you prefer, instead of creating a using block, you can call the Html.EndForm()     Helper method to close the <form> tag. Use whichever approach to creating an opening and closing <form> tag that seems most intuitive to you.
  The Html.TextBox() Helper methods are used in Listing 1 to render HTML <input> tags. If you select view source in your browser then you see the HTML source in Listing 2. Notice that the source contains standard HTML tags.

  IMPORTANT: notice that the Html.TextBox()-HTML  Helper is rendered with <%= %> tags instead of <% %> tags. If you don't include the equal sign, then nothing gets rendered to the browser.

  The ASP.NET MVC framework contains a small set of helpers. Most likely, you will     need to extend the MVC framework with custom HTML Helpers. In the remainder of this     tutorial, you learn two methods of creating custom HTML Helpers.

  Listing 2 – Index.aspx Source

<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Index" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> <head>
<title>Index</title>
</head>
<body>
<div>
<form action="http://localhost:33102/" method="post">
<label for="firstName">First Name:</label> <br />
<input id="firstName" name="firstName" type="text" value="" />
<br /><br />
<label for="lastName">Last Name:</label>
<br />
<input id="lastName" name="lastName" type="text" value="" />
<br /><br /> <input id="btnRegister" name="btnRegister" type="submit" value="Register" />
</form>
</div>
</body>
</html>

  Creating HTML Helpers with Static Methods

  The easiest way to create a new HTML Helper is to create a static method that returns     a string. Imagine, for example, that you decide to create a new HTML Helper that     renders an HTML <label> tag. You can use the class in Listing     2 to render a<label> .

  Listing 2 – Helpers\LabelHelper.cs

using System;
namespace MvcApplication1.Helpers
{
public class LabelHelper {
public static string Label(string target, string text)
{
return String.Format("<label for='{0}'>{1}</label>", target, text);
}
}
}

  There is nothing special about the class in Listing 2. The Label() method simply returns a string.

  The modified Index view in Listing 3 uses the LabelHelper to render HTML <label> tags. Notice that the view includes an<%@ imports         %> directive that imports the Application1.Helpers namespace.

  Listing 2 – Views\Home\Index2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index2.aspx.cs" Inherits="MvcApplication1.Views.Home.Index2"%>
<%@ Import Namespace="MvcApplication1.Helpers" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server"> <title>Index2</title>
</head>
<body>
<div>
<% using (Html.BeginForm())
{ %>
<%= LabelHelper.Label("firstName", "First Name:") %>
<br /> <%= Html.TextBox("firstName")%>
<br /><br />
<%= LabelHelper.Label("lastName", "Last Name:") %>
<br />
<%= Html.TextBox("lastName")%>
<br /><br />
<input type="submit" value="Register" />
<% } %> </div>
</body>
</html>

  Creating HTML Helpers with Extension Methods

  If you want to create HTML Helpers that work just like the standard HTML Helpers included in the ASP.NET MVC framework then you need to create extension methods.  Extension methods enable you to add new methods to an existing class. When creating an HTML Helper method, you add new methods to the HtmlHelper class represented by a view's Html property.

  The class in Listing 3 adds an extension method to the HtmlHelper class named Label(). There are a couple of things that you should notice about this class. First, notice that the class is a static class. You must define an extension method with a static class.

  Second, notice that the first parameter of the Label() method is preceded     by the keyword this. The first parameter of an extension method indicates     the class that the extension method extends.

Listing 3 – Helpers\LabelExtensions.cs

using System;
using System.Web.Mvc; namespace MvcApplication1.Helpers
{
public static class LabelExtensions
{
public static string Label(this HtmlHelper helper, string target, string text)
{
return String.Format("<label for='{0}'>{1}</label>", target, text); }
}
}

  After you create an extension method, and build your application successfully, the     extension method appears in Visual Studio Intellisense like all of the other methods of a class (see Figure 2). The only difference is that extension methods appear     with a special symbol next to them (an icon of a downward arrow).

  

  The modified Index view in Listing 4 uses the Html.Label() extension method to render     all of its <label> tags.

  Listing 4 – Views\Home\Index3.aspx

  

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index3.aspx.cs" Inherits="MvcApplication1.Views.Home.Index3" %>

<%@ Import Namespace="MvcApplication1.Helpers" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Index3</title>
</head>
<body>
<div> <% using (Html.BeginForm())
{ %>
<%= Html.Label("firstName", "First Name:") %>
<br />
<%= Html.TextBox("firstName")%>
<br /><br />
<%= Html.Label("lastName", "Last Name:") %>
<br />
<%= Html.TextBox("lastName")%> <br /><br />
<input type="submit" value="Register" />
<% } %>
</div>
</body>
</html>

 Summary

  In this tutorial, you learned two methods of creating custom HTML Helpers. First,     you learned how to create a custom Label() HTML Helper by creating     a static method that returns a string. Next, you learned how to create a custom     Label() HTML Helper method by creating an extension method on the HtmlHelper class.

  In this tutorial, I focused on building an extremely simple HTML Helper method.     Realize that an HTML Helper can be as complicated as you want. You can build HTML     Helpers that render rich content such as tree views, menus, or tables of database     data.

 
 
 

ASP.NET MVC- VIEW Creating Custom HTML Helpers Part 2的更多相关文章

  1. 【记录】ASP.NET MVC View 移动版浏览的奇怪问题

    ASP.NET MVC View 中的一段代码: <span id="span_Id">@Model.ID</span> 没什么问题吧,浏览器浏览正常,查看 ...

  2. ASP.Net MVC View

    ASP.Net MVC View(视图)   View视图职责是向用户提供界面.负责根据提供的模型数据,生成准备提供给用户的格式界面. 支持多种视图引擎(Razor和ASPX视图引擎是官方默认给出的, ...

  3. ASP.NET MVC View 和 Web API 的基本权限验证

    ASP.NET MVC 5.0已经发布一段时间了,适应了一段时间,准备把原来的MVC项目重构了一遍,先把基本权限验证这块记录一下. 环境:Windows 7 Professional SP1 + Mi ...

  4. ASP.NET MVC View中的标签(tag)

    在编辑View的时候会用到各种HTML标签,如<a>,<input>,<p>等待,这些标签在ASP.NET MVC中都有对应的编程语法,它叫Razor,它是帮助我们 ...

  5. 【DevExpress v17.2新功能预告】DevExtreme ASP.NET MVC新的强类型HTML Helpers

    在ASP.NET MVC中构建视图时,强类型HTML helpers非常有用.像@Html.TextBoxFor(m => m.FirstName)这样内置的Helper方法已经存在很长时间了, ...

  6. ASP.NET MVC View向Controller传值方式总结

    1:QueryString传值1)也可以使用new{}来为form的action增加querystring2)在controler里使用Request.QueryString["word&q ...

  7. ASP.NET MVC View向Controller提交数据

    我们知道使用MVC的一个很重的的用途就是把Controller和View之间进行解耦,通过控制器来调用不同的视图,这就注定了Controller和View之间的传值是一个很重的知识点,这篇博文主要解释 ...

  8. ASP.NET MVC View使用Conditional compilation symbols

    由于View(.cshtml)的运行时编译关系,在项目级别中定义的symbols是无法被直接使用的.需要在Web.config中添加compilerOptions(在View目录下的Web.confi ...

  9. ASP.NET MVC view引入命名空间

    两种方式:1,在cshtml中引入@using Admin.Models 2,在 Views 文件夹中的 Web.config 文件中添加引用如: <pages pageBaseType=&qu ...

随机推荐

  1. 在线小词典(mysql扩展库操作)

    输入英文查询中文 1.建表 create table words( id int primary key auto_increment, enWords varchar(32) not null, c ...

  2. 【Asp.Net】小BUG汇总[更新]

    目录结构 1.Dictionary<T>遍历 2.Asp.net网站部署在C盘无法上传下载文件 3.Asp.Net网站发布后远程无法访问 4.GDI+中发生一般性错误 1.Dictiona ...

  3. linux下安装php扩展redis缓存

    下载phpredis安装包 wget https://github.com/nicolasff/phpredis/tarball/master 在下载目录解压phpredis.tar.gz tar z ...

  4. 斗地主你什么时候才会托管?(.NET中的托管于非托管)

    文章部分引自<.NET4.0面向对象编程漫谈(基础篇)>第1章.NET面向对象编程基础(作者:金旭亮) 无意间看到一位四五岁左右小朋友在玩斗地主,总开始到结束,她一直都在使用“提示”(托管 ...

  5. C# Post Json数据

    public string Post(string Url, string jsonParas)    {        string strURL = Url; //创建一个HTTP请求       ...

  6. AppStore 审核中文版 --- 程序员必看

    App Store审核指南中文版(2014.10.11更新) 2014-11-03 程序猿 苹果在9月3日对App Store审核指南进行了重大更新,新添加了扩展.HealthKit.HomeKit以 ...

  7. Web应用的组件化(一)

    基本思路 1. 为什么要做组件化? 无论前端也好,后端也好,都是整个软件体系的一部分.软件产品也是产品,它的研发过程也必然是有其目的.绝大多数软件产品是追逐利润的,在产品目标确定的情况下,成本有两个途 ...

  8. uva 1335 - Beijing Guards

    竟然用二分,真是想不到: 偶数的情况很容易想到:不过奇数的就难了: 奇数的情况下,一个从后向前拿,一个从前向后拿的分配方法实在太妙了! 注: 白书上的代码有一点点错误 代码: #include< ...

  9. csu 10月 月赛 D 题 CX and girls

    Description CX是要赶去上课,为了不迟到必须要以最短的路径到达教室,同时CX希望经过的路上能看到的学妹越多越好.现在把地图抽象成一个无向图,CX从1点出发,教室在N号点,告诉每个点上学妹的 ...

  10. UIKIT网页基本结构学习

    没办法,哈哈,以后一段时间,如果公司没有招到合适的运维研发, 啥啥都要我一个人先顶上了~~~:) 也好,可以让人成长. UIKIT,BOOTSTRAP之类的前端,搞一个是有好处的,我们以前即然是用了U ...