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下有智能提示 显示出来:
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>
现在你可以运行下看效果了:
总结
在这篇POST中你学习了如何扩展HTML Helper类来创建自定义HTML
Author: Petter Liu