Forgive my bad english.
I have a project that contains signalR and JavaScript code. But the controller side called Clients.All.function_name (); not working.
My hub class:
public class yenile : Hub
{
public void sayfaYenile()
{
Clients.All.syenile();
}
}
My javascript code:
<script>
var sayfayenile = $.connection.yenile;
sayfayenile.client.syenile = $(function () {
$.ajax({
type: "GET",
url: '/hasta/',
data: {},
success: function (data) {
$("#con").html($(data).find("#con").html());
},
}
});
});
$.connection.hub.start().done(function () { console.log("connected"); });
</script>
IHubContext
public static IHubContext yenileContext = GlobalHost.ConnectionManager.GetHubContext<yenile>();
And calling the yenileContext
yenileContext.Clients.All.yenile();
My Startup class:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
Kindly you must refer signalr library files.Depend on your signlar verions you should change.
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-3.1.1.min.js" ></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
Second point: Your javascript reference must use camel case for calling your server class and its members function.
I found the cause of the error.
sayfayenile.client.syenile = $(function () instead of
sayfayenile.client.yenile = $(function ()
Related
I have created a ASP.NET Web Application (.Net Framework) in VS2017, I have selected an Empty project and ticked the Web API checkbox. I don't want MVC. I install from Nuget Microsoft.AspNet.SignalR. All is well. Then I
Add an OWIN Startup class and add the line app.MapSignalR(); in the Configuration method.
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(WebApplication4.Startup))]
namespace WebApplication4
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
I create a Hub called MyTestHub with a single method Activate.
using Microsoft.AspNet.SignalR;
namespace WebApplication4
{
public class MyTestHub : Hub
{
public string Activate()
{
return "Monitor Activated";
}
}
}
I create an html page to test with the following:
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.2.js"></script>
<script src="signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var notificationHub = $.connection.myTestHub;
$.connection.hub.start(function () {
notificationHub.activate(function (response) {
console.log("response", response);
});
});
});
</script>
The hub is created, $.connection.hub.start is fine, but notificationHub.activate returns "Object doesn't support property or method 'activate'". I cannot find the function on notificationHub but I do find it on notificationHub.server. However, calling notificationHub.server.activate does nothing.
I have tried the latest stable version of SingnalR and 2.2.2 (as the sample project) but nothing works. signalr/hibs is OK.
Any ideas? All the examples I have seen basically do this, but I cannot get it to work.
Found the answer
notificationHub.server.activate().done(function (response) {
console.log("response", response);
});
I want to update textarea from controller after i found some result and page should not be reload. Is there any solution for this?
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult SolveProblems(Problem[] array){
Solution sol=new Solution(array);
sol.OnSolutionFound+=sol_OnSolutionFound;
sol.OnTaskComplete+=sol_OnTaskComplete;
sol.Start();
return Json("Process started");
}
private void sol_OnSolutionFound(object sender, SolutionFoundEventArgs e)
{
// Here i want update textarea
}
private void sol_OnTaskComplete(object sender, SolutionCompletedEventArgs e)
{
// Here i want show process is finished
}
}
This is my html page. which contains some code and one textarea
..... some code....
<textarea class="form-control" id="ResultDisplay"></textarea>
<button type="button" id="btnSolve" class="btn btn-primary">Solve</button>
this is my javascript file
function GetProblems(){
...code...
return array;
}
$("#btnSolve").click(function () {
$.ajax({
type: "POST",
url: "/Home/SolveProblems",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(GetProblems()),
dataType: "json",
success: function (response) {
},
error: function (response) {
alert("Unexpected error occurs!")
}
});
});
So, I have use SignalR and solve my problem as freedomn-m told me to do
I need to create a Hub by using i can send data when sol_OnSolutionFound is fired.
Here is my Hub
public class SolutionHub : Hub
{
public void SolutionFound(string Solution)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<SolutionHub>();
hubContext.Clients.All.addNewMessageToPage(Solution);
}
}
Add section in Index.cshtml
#section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.solutionHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (Solution) {
// Add the message to the page.
$("#ResultDisplay").append(Solution);
};
$.connection.hub.start().done(function () {
});
});
</script>
}
and finally need to call SolutionFound when sol_OnSolutionFound is fired.
private void sol_OnSolutionFound(object sender, SolutionFoundEventArgs e)
{
SolutionHub Hub=new SolutionHub();
Hub.SolutionFound(e.Solution);
}
I am trying to get all usernames in jQuery autocomplete but it doesn't seem to work at all.
controller-
public ActionResult Allusers(string Email) {
if (ModelState.IsValid) {
var allUser = (from us in db.SystemUsers
select new UserModel
{
Email=us.Email,
UserId=us.UserId
}).Distinct().ToArray();
// ViewBag.Team = allUser.OrderBy(x => x.Text);
return Json(allUser,JsonRequestBehavior.AllowGet);
}
return View();
}
Script-
<script type="text/javascript">
$(function () {
$("input #autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
url: '/AllUsers/AllUsers/',
type: "POST",
dataType: "json"
});
}
});
});
</script>
Following scripts I am using for it-
<script src="../../Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>
But no luck.
Try as follows
<script type="text/javascript">
$(function () {
var itemList = [];
$("input #autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
url: '/AllUsers/AllUsers/',
type: "POST",
dataType: "json",
Sucess: function(result) {
$.each(result, function (index, item) {
itemList.push({ label: item.Email, value: item.UserId});
});
}
});
response(itemList);
}
});
});
You need to define success function and fill the response parameter
Refer to the JQuery autocomplete remote json
I was also stucked in this however below worked for me.
In my case my json result was array of string, so there was no column for the returned data.
If you are using .cshtml instead of html then you must have to add/register javascript and css files in bundle config
Render required files in your shared or respective cshtml file.
After that in your cshtml file add below line:
<input type='text' id='stockName'/>
Below part is very tricky and important:
$(function () {
$('#stockName').autocomplete({
source: function (request, response) {
$.getJSON("/EquityList/GetStockNames?term=" + request.term, function (data) {
var realArray = $.makeArray(data)
response($.map(realArray, function (item) {
return {
value: item,
id: item
}
}))
});
},
minLength: 3,
delay: 0
});
});
Important Note:
1) we need to format json data into array first
2) then we need to use map function, this well format the data in to the required format for autocomplete. Until and unless this data formatting is not done, suggestion dialog box UI will not be displayed.
Hope this one helps other developers.
My controller relies on a service which does http requests.
Both controller and service tests require the httpBackend with the same data. Do you have any idea of a workaround?
I imagine your code looks like this:
angular.module('MyApp', [])
.controller('MyCtrl', function($scope, MyService) {
$scope.doSomething = function() {
MyService.doSomething();
};
})
.service('MyService', function($http) {
$http.get('some-url')
.success(function(response) {
// Handles the response
});
});
In order to unit test MyCtrl you need to mock out its dependencies: $scope and MyService. So in your test you can do this:
describe('MyCtrl', function() {
var MyServiceMock,
scope;
beforeEach(function() {
module('MyApp');
// Creates a mock (spy) for MyService
MyServiceMock = jasmine.createSpyObj('MyService', ['doSomething']);
inject(function($provide) {
// Tells Angular to use MyServiceMock instead of MyService
$provide.value('MyService', MyServiceMock);
});
inject(function($controller, $rootScope) {
scope = $rootScope.$new();
$controller('MyCtrl', { $scope: scope });
});
});
it('calls doSomething of MyService', function() {
$scope.doSomething();
expect(MyServiceMock.doSomething).toHaveBeenCalled();
});
});
That way you can test MyCtrl without having to use an actual instance of MyService.
I assume you know how to write tests for MyService using the $httpBackend service, so I won't post the code for it here.
I have a simple MVC4 app where however I want to combine knockoutJS and SignalR and I got a challenge which seems to be caused by the fact that I'm trying to assign 2 onclick events on the same button: using knockoutJS and signalR. Please let me know what's wrong here. Below is the code.
This is my viewModel:
var viewModel = {
searchString: ko.observable("Monique"),
search: function () {
$.ajax({
url: "#Url.Action("Search")",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function (result) {
$('#info').append(result.message);
}
});
},
searchClient: function () {
//do sth
},
showAll: function () {
//do sth
}
};
ko.applyBindings(viewModel);
And this part is related to signalR:
This is my hub on a server:
[HubName("send")]
public class DataHub: Hub
{
public void Send(string text)
{
Clients.All.addMessage(text);
}
}
and this is a signalR js part:
$(function () {
var hub = $.connection.send;
hub.client.addMessage = function (text) {
alert(text);
$('#info').append(text);
};
$.connection.hub.start().done(function () {
$('#btnServer').click(function () {
alert('btn server clicked');
hub.server.send("something");
});
});
});
So as you can see, knockoutJS has onclick event processing here search: function () { }
and in signalR I also have $('#btnServer').click(function() {.
And as a result, what is related to knockoutJS works but the part related to signalR does not work...
In that function where you bind click event using knockout, return true. By default, Knockout will prevent the click event from taking any default action.