用于facebook的HtmlHelper扩展方法就像按钮一样

时间:2011-04-18 12:37:00

标签: asp.net-mvc asp.net-mvc-3 facebook-c#-sdk

2 个答案:

答案 0 :(得分:3)

我有一个类似的场景,我必须创建一个像Facebook一样的按钮(仅使用iframe)并且不需要任何其他程序集,这就是我最终做的事情:

代码:

    public static MvcHtmlString FacebookLikeButton(this HtmlHelper htmlHelper, string url, int width = 90, int height = 21, object htmlAttributes = null)
    {
        var tagBuilder = new TagBuilder("iframe");

        var uriBuilder = new UriBuilder("http://www.facebook.com/plugins/like.php");

        var nvc = new NameValueCollection
        {
            {"locale", Thread.CurrentThread.CurrentCulture.ToString().Replace("-", "_")},
            {"href", url},
            {"layout", "button_count"},
            {"show_faces", "true"},
            {"width", width.ToString(CultureInfo.InvariantCulture)},
            {"height", height.ToString(CultureInfo.InvariantCulture)},
            {"action", "like"},
            {"colorscheme", "light"},
            {"font", "arial"}
        };

        uriBuilder.Query = string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));

        tagBuilder.MergeAttribute("src", uriBuilder.Uri.AbsoluteUri);
        tagBuilder.MergeAttribute("scrolling", "no");
        tagBuilder.MergeAttribute("frameborder", "0");
        tagBuilder.MergeAttribute("style", string.Format("border:none; overflow:hidden; width:{0}px; height:{1}px;", width, height));
        tagBuilder.MergeAttribute("allowTransparency", "true");

        if (htmlAttributes != null)
        {
            tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        }

        var completeHtml = tagBuilder.ToString(TagRenderMode.Normal);

        return new MvcHtmlString(completeHtml);
    }

用法:

@Html.FacebookLikeButton(Model.AbsoluteUrl)

由于这篇文章相当陈旧,我猜你已经成功达到了你所希望的目标,尽管这篇文章是我在搜索主题时获得的第一个结果。

答案 1 :(得分:1)

您可以尝试使用Microsoft.Web.Helpers.dll中的帮助程序,只需使用NuGet下载该库。

这是一个链接:http://weblogs.asp.net/imranbaloch/archive/2010/11/07/using-asp-net-web-pages-in-asp-net-mvc.aspx