Skip to content

Using Needletail.Mvc

pedro-ramirez-suarez edited this page Jan 18, 2013 · 1 revision

Needletail.Mvc

Needletail.Mvc allows you to call javascript code anywhere from your MVC project, this is allows you to tell the client(browser) to call some function when an event occurs on the server's code in real time.

Only works with MVC 4 and with browsers that support SSE(sorry, no IE).

You need to add a reference to NeedletailMvc.js before make any call on the server.

Also, you need to initialize the library to point it where the controller that handles the communication is located, by default is the "RemoteController". An example of how to initialize the library using the default controller added by the nuget package:

/*Javascript code*/
    var twoway = '@Url.Action("Remote", "Api", new { })';
    needleTail.initialize(twoway);

To make remote calls you need to pass a ClientCall object to any of the mechanisms that allows you to call client's code, when you are initializing the object, define it as dynamic.

dynamic call = new ClientCall { ClientId = [Id of the client], CallerId = [Id of the caller] };
call.methodToCall(parameter, list, goes, here);

ClientId is optional, if empty, the call will be broadcasted to all the connections, CallerId is also optional, set this property when you need to know who made the call in the case that the call failed.

To send messages from the server, you have two options, you can return an TwoWayResult from your controller like this:

public TwoWayResult SendMessageTo(string messageTo, string message)
{
	dynamic call = new ClientCall { ClientId = messageTo, CallerId = User.Identity.Name };
	//make the remote call
	call.messageReceived(User.Identity.Name, message , true);
	return new TwoWayResult(call);
}

You can call js funcions defined anywhere in your javascript, you can also make calls to functions contained in a namespace like this:

	   dynamic call = new ClientCall { ClientId = messageTo, CallerId = User.Identity.Name };
	//make the remote call
	call.sample.of.namespace.call(parameter1, parameter2, etc);
	return new TwoWayResult(call);

You can also make a call from anywhere in the server's code like this:

public static void ReloadUserList()
{
	dynamic reload = new ClientCall { CallerId = string.Empty, ClientId = string.Empty };
	reload.getUsers();
	RemoteExecution.BroadcastExecuteOnClient(reload);
}		       

You can find a simple chat application here: https://github.com/pedro-ramirez-suarez/Needletail.Mvc.Sample

Clone this wiki locally