我们基于Asp.net MVC 4 Web Application 写一个扩展方法来呈现图片的扩展。​​Gravatar​​是提供个人Profile信息的网站,包括图片LOGO。你可以引用你的Profile到论坛,Blog都可以。

        一开始我们写一个Helper如下:


1:  namespace MVC4Demo.Extensions
2:  {
3:      using System;
4:      using System.Web.Mvc;
5:      using System.Web.Security;
6:
7:      public static class GravatarHtmlHelperExtensions
8:      {
9:          /// <summary>
10:          /// Gets the Gravatar image URL.
11:          /// </summary>
12:          /// <param name="emailId">The email id.</param>
13:          /// <param name="imgSize">Size of the img.</param>
14:          /// <seealso cref="https:///"/>
15:          /// <returns>Image MvcHtmlString</returns>
16:          public static MvcHtmlString RenderGravatarImage(this HtmlHelper helper, string emailId, int imgSize)
17:          {
18:              if (string.IsNullOrEmpty(emailId))
19:                  throw new ArgumentNullException("Email Id should not be null!");
20:
21:              // Convert emailID to lower-case
22:              emailId = emailId.ToLower();
23:
24:              string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(emailId, "MD5").ToLower();
25:
26:              // build Gravatar Image URL
27:              string imageUrl = string.Format(@"<img src=""http:///avatar/{0}?s={1}&d=mm&r=g"" />", hash, imgSize);
28:
29:              return new MvcHtmlString(imageUrl);
30:          }
31:      }
32:  }



接在​​Razor​​的Web.config中加入相应的Namespace:



<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="MVC4Demo.Extensions"/>
</namespaces>
</pages>
</system.web.webPages.razor>



然后在页面cshtml上我们可以这样使用了:


<div class="Author" style="position:relative;">
<div style="position:absolute; top:10px;">
@Html.RenderGravatarImage(Model.AuthorEmail, 100)
</div>



如果您对Asp.net MVC 4 Web Application有一定了解,上面的代码并不难懂,这里也只是非常简单的一个示例。希望对您开发有帮助。



作者:​​Petter Liu​