热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ASP.NETMVCVIEWCreatingCustomHTMLHelpersPart2

ThegoalofthistutorialistodemonstratehowyoucancreatecustomHTMLHelpers    thatyoucanusewithinyourMVCviews.BytakingadvantageofHTMLHelpers,youcanreducetheamo

  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 and 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.

ASP.NET MVC- VIEW Creating Custom HTML Helpers Part 2

Listing 1 – Views\Home\Index.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index"%>
"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

"http://www.w3.org/1999/xhtml ">
"Head1" runat="server">
     


      
<% using (Html.BeginForm()) { %>
<%= Html.TextBox("firstName")%>


<%= Html.TextBox("lastName")%>

"submit" value="Register" /> <% } %> 1

  The Html.BeginForm() Helper method is used to create the opening and closing HTML tags. Notice that the Html.BeginForm() method is called within a using statement. The using statement ensures that the 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 tag. Use whichever approach to creating an opening and closing tag that seems most intuitive to you.
  The Html.TextBox() Helper methods are used in Listing 1 to render HTML 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" %>
"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
"http://www.w3.org/1999/xhtml">


     


     
"http://localhost:33102/" method="post">
"firstName" name="firstName" type="text" value="" />


"lastName" name="lastName" type="text" value="" />

"btnRegister" name="btnRegister" type="submit" value="Register" />

  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 tag. You can use the class in Listing     2 to render a .

  Listing 2 – Helpers\LabelHelper.cs

using System;
namespace MvcApplication1.Helpers
{
          public class LabelHelper

          {
               public static string Label(string target, string text)
               {
                    return String.Format("", 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 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" %>
"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
"http://www.w3.org/1999/xhtml" >
"Head1" runat="server">

     


     
<% using (Html.BeginForm()) { %> <%= LabelHelper.Label("firstName", "First Name:") %>
<%= Html.TextBox("firstName")%>

<%= LabelHelper.Label("lastName", "Last Name:") %>
<%= Html.TextBox("lastName")%>

"submit" value="Register" /> <% } %>

  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("", 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).

  ASP.NET MVC- VIEW Creating Custom HTML Helpers Part 2

  The modified Index view in Listing 4 uses the Html.Label() extension method to render     all of its 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" %>
"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
"http://www.w3.org/1999/xhtml" >
"Head1" runat="server">
     


     
<% using (Html.BeginForm()) { %> <%= Html.Label("firstName", "First Name:") %>
<%= Html.TextBox("firstName")%>

<%= Html.Label("lastName", "Last Name:") %>
<%= Html.TextBox("lastName")%>

"submit" value="Register" /> <% } %>

 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.

 
 
  原文网址:http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs
 

推荐阅读
  • Ihavethefollowingonhtml我在html上有以下内容<html><head><scriptsrc..3003_Tes ... [详细]
  • 本文介绍了Perl的测试框架Test::Base,它是一个数据驱动的测试框架,可以自动进行单元测试,省去手工编写测试程序的麻烦。与Test::More完全兼容,使用方法简单。以plural函数为例,展示了Test::Base的使用方法。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • 拥抱Android Design Support Library新变化(导航视图、悬浮ActionBar)
    转载请注明明桑AndroidAndroid5.0Loollipop作为Android最重要的版本之一,为我们带来了全新的界面风格和设计语言。看起来很受欢迎࿰ ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • 本文介绍了Swing组件的用法,重点讲解了图标接口的定义和创建方法。图标接口用来将图标与各种组件相关联,可以是简单的绘画或使用磁盘上的GIF格式图像。文章详细介绍了图标接口的属性和绘制方法,并给出了一个菱形图标的实现示例。该示例可以配置图标的尺寸、颜色和填充状态。 ... [详细]
  • 本文介绍了Sencha Touch的学习使用心得,主要包括搭建项目框架的过程。作者强调了使用MVC模式的重要性,并提供了一个干净的引用示例。文章还介绍了Index.html页面的作用,以及如何通过链接样式表来改变全局风格。 ... [详细]
  • Asp.net Mvc Framework 七 (Filter及其执行顺序) 的应用示例
    本文介绍了在Asp.net Mvc中应用Filter功能进行登录判断、用户权限控制、输出缓存、防盗链、防蜘蛛、本地化设置等操作的示例,并解释了Filter的执行顺序。通过示例代码,详细说明了如何使用Filter来实现这些功能。 ... [详细]
  • wpf+mvvm代码组织结构及实现方式
    本文介绍了wpf+mvvm代码组织结构的由来和实现方式。作者回顾了自己大学时期接触wpf开发和mvvm模式的经历,认为mvvm模式使得开发更加专注于业务且高效。与此同时,作者指出mvvm模式相较于mvc模式的优势。文章还提到了当没有mvvm时处理数据和UI交互的例子,以及前后端分离和组件化的概念。作者希望能够只关注原始数据结构,将数据交给UI自行改变,从而解放劳动力,避免加班。 ... [详细]
  • 本文介绍了如何使用PHP向系统日历中添加事件的方法,通过使用PHP技术可以实现自动添加事件的功能,从而实现全局通知系统和迅速记录工具的自动化。同时还提到了系统exchange自带的日历具有同步感的特点,以及使用web技术实现自动添加事件的优势。 ... [详细]
  • vue使用
    关键词: ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
author-avatar
好的吧
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有