Pomster
Pomster

Reputation: 15197

Razor to talk to class function?

I am trying to add social networking buttons to my site and have build a socialNetworkingHelper class.

I would like to know what i need to do to get the view to see the helper class.

I followed the following link to get where i am now.

http://www.advancesharp.com/Blog/1033/add-facebook-twitter-and-google-plus-in-c-mvc-application

I am using MVC 4 and have placed this div in my layout page in my footer.

<div>
   @Html.SocialLinkButtons(Model.Title, Request.Url.ToString())
</div>

The SocialLinkButtons text is underlined in red with the following error message.

'System.Web.Mvc.HtmlHelper' does not contain a definition for 'SocialLinkButtons' and no extension method 'SocialLinkButtons' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)

Is there somthing i must add to my view to allow the @html to call my socialLinkButtons? Or is there something i need to add to my class to allow this?

I have tried placing my class in the contoller folder and the models folder and just plain in the whole project. Where should this helper class be kept?

To see the class please follow the link placed above.

Edit:


Following the answers below the SocialLinkButtons text is no longer underlined but when i run my code i get the following error.

'System.Web.Mvc.HtmlHelper' has no applicable method named 'SocialLinkButtons' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

Upvotes: 0

Views: 1015

Answers (2)

YD1m
YD1m

Reputation: 5895

You shoud to put code from link in any namespace:

namespace Helpers {
  public static class SocialNetworkingHelper {
    ...
  }
}

and add using directive in your view:

@using Helpers

Upvotes: 3

Oleksandr Kobylianskyi
Oleksandr Kobylianskyi

Reputation: 3380

Probably you extension method SocialLinkButtons is not visible in the view. You should add @using MyNamespace directive in the view where MyNamespace is actual namespace of your extension method SocialLinkButtons or youcan achieve the same thing via web.config by adding this namespace to

<system.web.webPages.razor>
    <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.Routing" />
            <add namespace="System.Collections" />
            <add namespace="MyNamespace" />
        </namespaces>
    </pages>
</system.web.webPages.razor>

Upvotes: 1

Related Questions