JazzMaster
JazzMaster

Reputation: 717

Cannot implicitly convert type 'void' to 'object' MVC cshtml method call

I'm having some some problem calling a simple method from a cshtml file in a Mvc-Project. This is the code that is givnng me the error:

@{
var chatHub = new TestClass();
}
@chatHub.TestMethod();

It's the "@chatHub.TestMethod();" that's givning me the "Cannot implicitly convert type 'void' to 'object'" error.

This is TestMethod:

public void TestMethod()
        {
            ChatHub test = new ChatHub();
            //var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            test.JoinGrupprum1();
        }

And this is Joingrupprum1:

public void JoinGrupprum1()
        {
            Groups.Add(Context.ConnectionId, "Grupprum1");
        }

Any idea what's the problem?

Upvotes: 3

Views: 10232

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

With the @ before @chatHub.TestMethod(); you're instructing Razor to print the result of chatHub.TestMethod() to the HTML. In order to print something, it calls object.ToString() on the result.

However, your method is void and thus doesn't return anything. If you don't intend anything to be printed, move it inside the braces:

@{
    var chatHub = new TestClass();
    chatHub.TestMethod();
}

Upvotes: 14

Related Questions