ASP.NET MVC扩展HtmlHelper方法

在上一篇文章的最后,列出了一些常见的HtmlHelper的方法,这些都是ASP.NET MVC已经定义好的,如果我们想自己定义一个HtmlHelper方法可以吗?答案是肯定的,那么如何自定义一个HtmlHelper方法呢?

以Label()方法为例,查看Label方法的定义:

internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null, IDictionary<string, object> htmlAttributes = null)
{
            string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            if (String.IsNullOrEmpty(resolvedLabelText))
            {
                return MvcHtmlString.Empty;
            }

            TagBuilder tag = new TagBuilder("label");
            tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
            tag.SetInnerText(resolvedLabelText);
            tag.MergeAttributes(htmlAttributes, replaceExisting: true);
            return tag.ToMvcHtmlString(TagRenderMode.Normal);
}

这是MVC的源码中对Label()扩展方法的定义,我们可以参考MVC中源码定义扩展方法的方式自定义一个扩展方法。

下面以span标签为例进行扩展,扩展方法定义如下:

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

namespace MvcHtmlHelper.Helper
{
    /// <summary>
    /// HTML的扩展类
    /// </summary>
    public static class HtmlHelperExt
    {
        /// <summary>
        /// 用C#代码自定义一个span标签的扩展方法
        /// </summary>
        /// <param name="htlper"></param>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="style"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static MvcHtmlString Messager(this HtmlHelper htlper, string id,string name, string style, object message)
        {
            if (message != null)
            {
                TagBuilder builder = new TagBuilder("span");
                builder.MergeAttribute("style", style); //定义样式
                builder.MergeAttribute("id", id);     // 定义Id
                builder.MergeAttribute("name", name);  // 定义name
                builder.SetInnerText(message.ToString());
                //ToMvcHtmlString是在TagBuilderExtensions扩展类中定义的
                return builder.ToMvcHtmlString(TagRenderMode.Normal);
            }
            return MvcHtmlString.Empty;
        }
    }
}

TagBuilderExtensions扩展方法定义如下:

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

namespace MvcHtmlHelper.Helper
{
    public static class TagBuilderExtensions
    {
        public static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode)
        {
            System.Diagnostics.Debug.Assert(tagBuilder != null);
            return new MvcHtmlString(tagBuilder.ToString(renderMode));
        }
    }
}

视图页面代码如下:

@using MvcHtmlHelper.Helper;
@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="https://asp.net" rel="external nofollow"  class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
    <p>
        <!--使用自定义的Messager方法-->
        @Html.Messager("lblMessage", "lblMessage", "color:red;font-weight:bold;", "自定义span标签")
    </p>
</div>

<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.
        </p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865" rel="external nofollow" >Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866" rel="external nofollow" >Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867" rel="external nofollow" >Learn more &raquo;</a></p>
    </div>
</div>

运行结果如下:

到此这篇关于ASP.NET MVC扩展HtmlHelper方法的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • ASP.NET MVC HtmlHelper如何扩展

    一.ASP.NET 扩展方法三要素 (1).静态类 可以从下图看出,InputExtension首先是一个静态类: (2).静态方法 既然是静态类,那么其所有的方法必然都是静态方法,例如:public static MvcHtmlString CheckBox(): (3).this关键字 可以从方法名定义中看出,第一个参数都是this HtmlHelper htmlHelper,代表对HtmlHelper类的扩展: 二.通过 MVC  HtmlHelper扩展 实例简单说明扩展步骤 实例1.扩

  • ASP.NET MVC中HtmlHelper控件7个大类中各个控件使用详解

    HtmlHelper类在命令System.Web.Mvc.Html之中,主要由7个静态类组成,它们分别是FormExtensions类,InputExtensions类,LinkExtensions类,SelectExtensions类,TextExtensions类,ValidationExtensions类,RenderPartialExtensions类. 为了方便开发者使用HtmlHelper控件,在视图ViewPage类中设置了一个属性Html它就是HtmlHelper类型. 一.Fo

  • C# 封装HtmlHelper组件:BootstrapHelper

    前言:之前学习过很多的Bootstrap组件,博主就在脑海里构思:是否可以封装一套自己Bootstrap组件库呢.再加上看到MVC的Razor语法里面直接通过后台方法输出前端控件的方式,于是打算仿照HtmlHelper封装一套BootstrapHelper,今天只是一个开头,讲述下如何封装自己的Html组件,以后慢慢完善. 一.揭开HtmlHelper的"面纱" 经常使用Razor写法的园友都知道,在cshtml里面,我们可以通过后台的方法输出成前端的html组件,比如我们随便看两个例

  • MVC HtmlHelper扩展类(PagingHelper)实现分页功能

    MVC HtmlHelper扩展类PagingHelper实现分页功能,供大家参考,具体内容如下 using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace H

  • 一步一步封装自己的HtmlHelper组件BootstrapHelper(二)

    前言:上篇介绍了下封装BootstrapHelper的一些基础知识,这篇继续来完善下.参考HtmlHelper的方式,这篇博主先来封装下一些常用的表单组件.关于BootstrapHelper封装的意义何在,上篇评论里面已经讨论得太多,这里也不想过多纠结.总之一句话:凡事有得必有失,就看你怎么去取舍.有兴趣的可以看看,没兴趣的权当博主讲了个"笑话"吧. BootstrapHelper系列文章目录 C#进阶系列--一步一步封装自己的HtmlHelper组件:BootstrapHelper

  • asp.net 图片验证码的HtmlHelper

    一个图片验证码的HtmlHelper,原来的调用代码如下: 复制代码 代码如下: <img id="validateCode" mailto:src='@Url.Action(%22GetValidateCode%22)'/> <script language="javascript" type="text/javascript"> $(document).ready(function () { $("#vali

  • ASP.NET MVC4 HtmlHelper扩展类,实现分页功能

    1.扩展HtmlHelper类方法ShowPageNavigate public static HtmlString ShowPageNavigate(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount) { var redirectTo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath; page

  • 一步一步封装自己的HtmlHelper组件BootstrapHelper(三)

    前言:之前的两篇封装了一些基础的表单组件,这篇继续来封装几个基于bootstrap的其他组件.和上篇不同的是,这篇的有几个组件需要某些js文件的支持. BootstrapHelper系列文章目录 C#进阶系列--一步一步封装自己的HtmlHelper组件:BootstrapHelper C#进阶系列--一步一步封装自己的HtmlHelper组件:BootstrapHelper(二) C#进阶系列--一步一步封装自己的HtmlHelper组件:BootstrapHelper(三:附源码) 一.Nu

  • ASP.NET MVC扩展HtmlHelper方法

    在上一篇文章的最后,列出了一些常见的HtmlHelper的方法,这些都是ASP.NET MVC已经定义好的,如果我们想自己定义一个HtmlHelper方法可以吗?答案是肯定的,那么如何自定义一个HtmlHelper方法呢? 以Label()方法为例,查看Label方法的定义: internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string

  • IIS部署asp.net mvc网站的方法

    iis配置简单的ASP.NET MVC网站,供大家参考,具体内容如下 编译器:VS 2013 本地IIS:IIS 7 操作系统:win 7 MVC版本:ASP.NET MVC4 sql server版本: 2008 r2 打开VS 2013,新建一个MVC项目(Internet版的),然后在本地上运行测试下,应该可以.随后配置iis 7: 看看simple_mvc 下的内容(如果这里没有配置正确,就会出现分析器问题!): 先配置下目录浏览: 由于是MVC项目,我们可以不用配置默认文档 然后我们浏

  • ASP.NET mvc异常处理的方法示例介绍

    1.首先常见保存异常的类(就是将异常信息写入到文件中去) 复制代码 代码如下: public class LogManager { private string logFilePath = string.Empty; public LogManager(string logFilePath) { this.logFilePath = logFilePath; FileInfo file = new FileInfo(logFilePath); if (!file.Exists) { file.C

  • ASP.NET MVC使用Ajax的辅助的解决方法

    前言:前面我们已经简单的介绍过了MVC如何Jquery,因为我们如果使用Ajax的话必须要了解Jquery,这篇博客我们将大致了解一下ASP.NET MVC如何使用Ajax的辅助方法,此博客是我的读书笔记,如果那里写的不好,还请各位朋友提出来,我们共同学习.1.准备工作 (1)在MVC刚开始学习的时候,我们就需要介绍ASP.NET MVC框架中的HTML的辅助方法,但是这类文章现在已经很多了,而且个人感觉很简单,所以没有写笔记,我在这里就不介绍了. (2)ASP.NET MVC框架中的HTML辅

  • Asp.net MVC scheduler的实现方法详解

    Asp.net MVC scheduler的实现方法详解 本例使用了fullcalendar js : https://fullcalendar.io/ 1. view : @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } @section PageContent{ <style> .modal-backdrop { z-index: 9; } </sty

  • asp.net mvc webapi 实用的接口加密方法示例

    在很多项目中,因为webapi是对外开放的,这个时候,我们就要得考虑接口交换数据的安全性. 安全机制也比较多,如andriod与webapi 交换数据的时候,可以走双向证书方法,但是开发成本比较大, 今天我们不打算介绍这方面的知识,我们说说一个较简单也较常见的安全交换机制 在这里要提醒读者,目前所有的加密机制都不是绝对的安全! 我们的目标是,任何用户或者软件获取到我们的webapi接口url后用来再次访问该地址都是无效的! 达到这种目标的话,我们必须要在url中增加一个时间戳,但是仅仅如此还是不

  • ASP.NET MVC 使用Bootstrap的方法

    作为一名Web开发者而言,如果不借助任何前端框架,从零开始使用HTML和CSS来构建友好的页面是非常困难的.特别是对于Windows Form的开发者而言,更是难上加难. 正是由于这样的原因,Bootstrap诞生了.Twitter Bootstrap为开发者提供了丰富的CSS样式.组件.插件.响应式布局等.同时微软已经完全集成在ASP.NET MVC 模板中. Bootstrap结构介绍 你可以通过http://getbootstrap.com.来下载最新版本的Bootstrap. 解压文件夹

  • Asp.net MVC中Razor常见的问题与解决方法总结

    前言 最近在学习Asp.net MVC Razor,在使用中遇到了不少的问题,所以想着总结下来,没有经验的童鞋就是这样磕磕碰碰出来的经验.话不多说,来一起看看详细的介绍: 一.Datatype的错误提示消息无法自定义 这也许是Asp.net MVC的一个Bug.ViewModel中定义了DataType为Date字段: [Required(ErrorMessage = "Birthday must be input!")] [DataType(DataType.Date, ErrorM

  • Asp.net MVC定义短网址的方法

    在MVC的逻辑代码里,Controller和Action是必须的,但是在网址里,并不需要完全体现Controller和Action.比如我们经常希望看到http://localhost/About而不是http://localhost/Home/About. 默认的路由规则 新建MVC应用程序后,Global.asax里默认注册的路由规则是: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRout

随机推荐