Asynchronous calls with AjaxPro - asynchronous

I have been working with synchronous calls in AjaxPro, and I am now looking into asynchronous calls. I have been looking at the example Here
My question is : How do I pass variables to my ajaxpro method?
I would like to add some properties to the AjaxMethod MyMethod :
<script type="text/javascript">
function callback(res) {
alert(res.value);
}
function invokeMyMethod() {
Namespace.Classname.MyMethod(callback);
}
</script>

Your server-side method will look like this:
public void MyMethod(int param1, string param2, ...)
You need to call this from the client like so:
Namespace.Classname.MyMethod(param1, param2, callback);
That should do it.

Related

SignalR - How to call server function with parameter from client using hubproxy

I have my signalr running on a separate domain. We will have multiple applications using it to send and receive messages. I created the connection and hub proxy using the following code
connection = $.hubConnection("https://someurl.com", { useDefaultPath: false });
chatHub = connection.createHubProxy('chatHub');
I can get messages from the server sent to the client using the following code which works fine
chatHub.on('receiveEntityMessage', function (chatMessage) {
if (chatMessage) {
console.log(chatMessage.Message);
}
});
Now I dont know how to call server functions with parameters from the client. Can anybody please help me with this?
chatHub.invoke("MethodName", param1, param2, param3).done(function(result) {
console.log(result);
});
Since i'm not sure what is the language of your server side, i am going to provide a C# example.
C# Hub method example:
public class chatHub: Hub {
public void YourHubMehotd(int firstParam, string secondParam){
//The action of your method
}
}
JS client side:
You can call your hub method like this:
{The variable with the hub connection}.server.{the method you want to call}( {the parameters} )
Example:
chatHub.server.YourHubMehotd(1,"Example");
I recomend to create a js function to call the hub method.
function callMyHubMethod(firstParam, secondParam){
chatHub.server.YourHubMehotd(firstParam, secondParam);
}

ASP MVC - How to route directly to function instead of through get/post

I am working on a project in VS 2013 using ASP.NET MVC. In one of my cshtml files, I have the following code to return a value (here, and integer):
$.ajax({
url: '/myproject/api/Test',
type: 'GET',
success: function (data) {
UseResults(data);
},
error: function (msg) {
alert(msg);
}
});
The file this routes to, TestController.cs, has this code:
namespace MyProject.Controllers
{
public class TestController : ApiController
{
public int Get()
{
return GetThisValue();
}
public int GetThisValue()
{
//Do work to find and return value...
}
}
}
This code currently works properly. It does so by having the ajax call route to the Get() function, which returns the correct value from the GetThisValue() function. However, it is tedious to need the separate Get() function when all it does is call another function. Also, in this program, there will be many different functions using the "GET" method in Ajax, and while it would be possible to route them all through Get(), it would be a lot less cluttered for us to be able to call GetThisValue() directly in the ajax call instead of through Get(). My question is, is there any way to use ajax to route directly to a function that uses [HttpGet] instead of needing it to route first to Get() and then to the other function from there? (Sorry if I didn't put this into words great, if clarification is needed on anything please ask)
It's easy with attribute routing...
[Route("/myproject/api/test")]
[Route("/some/other/route")]
[Route("/yet/another/route")]
public int GetThisValue()
{
//Do work to find and return value...
}
You can set up all the separate routes you want to point to that same method.

I want to use JavaScript value as argument of Controller function, how can I figure it out?

This is a controller function:
public static void func(int id){
//some code
}
and this is a JavaScript function:
function notificationDivPressed(element,n) {
$(".NotificationDiv").removeAttr("style").children().removeAttr("style");
element = jQuery(element);
element.css("background", "#00b98d");
element.children().css("color", "white");
#MvcApplication.Controllers.MyController.func(n);
}
I want to do something like that... (use the "n" value a argument of "func" function from Controller)...
MVC controler are http paths you cannot call a function in the controller you need to call a post or a get Method. This can be accomplished using ajax
Small snipit
in controlerr create method that looks like this
[HttpPost]
public string Operation(string arg)
{
return "";
}
in View ".cshtml" you can call this using ajax
I usualy take the lazy way out and use jquery
$.ajax({
url: path to controler + '/Operation',
type: "POST",
cache: false,
data: {arg:'Argument Value'},
success: function (data)
{
}});
you could add error handling in the jquery if you like.

SignalR callback in javascript

Is there a way to pass a callback function for SignalR? Right now I have on my site.js
messageHub.client.sendProgress = function (progress) {
//doSomething with progress
}
What I would like to have is
messageHub.client.sendProgress = function (progress,callback) {
callback(progress);
}
This would enable me to define different callback functions from web pages for the same signalR method.
Right now I am doing it in kind of a hack-ish way by defining a function on my web page
function fnSendProgress(progress) //define this for site.js.
{
//do something here
}
and then in site.js calling it by
messageHub.client.sendProgress = function (progress) {
debugger;
//have a definition of a function called fnSendProgress(progress)
//if found it will call it else call default
if (typeof fnSendProgress == 'function') {
fnSendProgress(progress);
}
else {
//do something at site.js level
}
};
It works, but I was wondering if there is a cleaner method.
Any help much appreciated.
Use closures:
function createfunction(callback)
{
return function(progress) { callback(progress); }
}
messageHub.client.sendProgress = createFunction(callback)
First you define a function "createFunction", which given a callback returns another function with one argument, which calls the specified callback.
Then you assign the result of calling that function to signalr's sendProgress.
In other words: for each callback you want you dynamically generate a function with one argument, which calls the callback and passes the argument to it.

Is there a way to exclude a Client from a Clients.method call in SignalR?

I am evaluating SignalR (which happens to be used with Knockoutjs) to see if we can use it to notify clients of concurrency issues. Basically user "a" saves a record and users "b,c,d,e,f,g" are notified. I basically have an example working that notifies all clients. So I think I am almost there.
I came across this link and it lead me on the current path that I am on. I have also been looking at the documentation on Github.
Basically I want to exclude the a single client from the Clients.method() call. I dont see a way to loop through the clients and check the ClientId. The only other I can see to accomplish this is to maybe look at using the groups to keep track of it, but that seemed a little cumbersome, but I was having issues with that as well.
public class TicketHub : Hub
{
static int TotalTickets = 10;
public void GetTicketCount()
{
AddToGroup("ticketClients");
Clients.setTicketCount(TotalTickets);
}
public void BuyTicket()
{
if (TotalTickets > 0)
TotalTickets -= 1;
RemoveFromGroup("ticketClients");
// This will call the method ONLY on the calling client
// Caller.updateTicketCountWithNotification(TotalTickets);
// This will call the method on ALL clients in the group
Clients["ticketClients"].updateTicketCountNotify(TotalTickets);
AddToGroup("ticketClients");
Caller.updateTicketCountDontNotify(TotalTickets);
}
}
javascript code:
<script type="text/javascript">
$(document).ready(function () {
var test = $.connection.test;
$("#btnTest").click(function () {
test.testMethod();
});
test.show = function (text, guid) {
if (guid != test.guid) //notify all clients except the caller
alert(text);
};
$.connection.hub.start(function () { test.start(); });
});
</script>
Class :
public class Test : Hub
{
public void Start()
{
Caller.guid = Guid.NewGuid();
}
public void TestMethod()
{
Clients.show("test", Caller.guid);
}
}
If you want to exclude the caller from the call to the client side method you can use:
Clients.Others.clientSideMethod();
There is also Clients.AllExcept(...) that allows excluding certain people.

Resources