zoukankan      html  css  js  c++  java
  • 在Asp.net MVC framework中使用扩展方法创建Html Helper

             HtmlHelper提供了一些帮助的方法返回一个字符串来生成html. 在System.Web.Mvc.Html命称空间下有一些表单,控件,局部视图Helper方法.我将创建一个生成标签<input type=”submit”,名称为SubmitConfirmHelper的类.看下面:

    using System.Web.Mvc;
    namespace Helpers
    {
        public static class SubmitConfirmHelper
        {
            /// <summary> 
            /// Renders an HTML form submit confirm button 
            /// </summary> 
            public static string SubmitConfirm(this HtmlHelper helper, string buttonText, string alertMessage)
            {
                return String.Format("<input type=\"submit\" value=\"{0}\" onClick=\"return confirm('{1}');\" />", buttonText, alertMessage);
            }
        }
    }

    因为SubmitConfirm()方法扩展自HtmlHelper类,所以这个方法在HtmlHelper下有智能提示 显示出来:

    mvc_1

    View使用Html.SubmitConfirm()方法来呈现submit 按钮

    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> 
    <%@ Import Namespace="Helpers"%> 
    <asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server"> 
        About Us 
    </asp:Content> 
    <asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server"> 
        <h2>About</h2> 
        <p> 
        <% using (Html.BeginForm()) { %> 
          <%=  Html.SubmitConfirm("Delete", "Do you want to delete?")%> 
        </p> 
         <% } %> 
    </asp:Content> 

    现在你可以运行下看效果了:

    mvc_2

    总结

    在这篇POST中你学习了如何扩展HTML Helper类来创建自定义HTML


    Author: Petter Liu    http://wintersun.cnblogs.com

  • 相关阅读:
    在Windows上搭建Git Server
    Windows环境下Zookeeper 的安装与配置
    错误: 找不到或无法加载主类 org.apache.zookeeper.server.quorum.QuorumPeerMain
    windows环境搭建dubbo服务
    gunicorn 使用
    jQuery 插件autocomplete 应用
    PHP str_replace() 函数详解
    jQuery的deferred对象详解
    Elasticsearch tp5使用
    MySQL explain详解
  • 原文地址:https://www.cnblogs.com/wintersun/p/1530923.html
Copyright © 2011-2022 走看看