.NET MVC 中创建自定义 HtmlHelper(带源码)
1.创建PageHelper类:
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Web; 6 using System.Web.Mvc; 7 using System.Web.Mvc.Html; 8 9 namespace MvcHtmlHelper 10 { 11 public static class PageHelper 12 { 13 public static MvcHtmlString RenderView(this HtmlHelper htmlHelper,string fileName) 14 { 15 string fullfilename = HttpContext.Current.Server.MapPath(fileName); 16 if(File.Exists(fullfilename)) 17 { 18 return PartialExtensions.Partial(htmlHelper, fileName); 19 } 20 else 21 { 22 return null; 23 } 24 } 25 } 26 }
2.在Views文件夹下面随意创建一个视图MyView.cshtml
3.视图中调用方式:
1 @{ 2 ViewBag.Title = "Index"; 3 } 4 @using MvcHtmlHelper; 5 <h2>Index</h2> 6 7 @*调用方法1*@ 8 @*@PageHelper.RenderView(this.Html,"~/Views/MyView.cshtml")*@ 9 10 @*调用方法2*@ 11 @Html.RenderView("~/Views/MyView.cshtml")