Based on various resources the signalr code should be working, but I can't make it to send notifications from the server to client. Here is html/javascript part:
<script src="/Scripts/jquery-1.6.4.min.js"></script>
<script src="/Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="/signalr/js"></script>
<script type="text/javascript">
$(function () {
var cHub = $.connection.cHub;
$.connection.hub.logging = true;
cHub.client.sendMessage = function (content) {
$("#container-hub").append($("<p />").html(content));
};
$.connection.hub.start().done(function() {
$('[id$=bGo]').click(
function() {
cHub.server.send('Sync process started');
});
});
});
</script>
<div id="container-hub" style="background: red; height: 100px; width: 100%;"></div>
Hub.cs class:
using Microsoft.AspNet.SignalR;
namespace CMS.Objects
{
public class CHub : Hub
{
public void Send(string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.sendMessage(message);
}
}
}
Startup.cs class:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(CMS.CStartup))]
namespace CMS
{
public class CStartup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
And here is how I am calling the method sendMessage method:
private void ShowMessage(string message)
{
var clients = GlobalHost.ConnectionManager.GetHubContext<CHub>().Clients;
clients.All.sendMessage(message);
}
When the button bGo is clicked the message is getting appended to the container-hub div, but nothing when I call sendMessage method.
EDIT
Some additional findings; when I call sendMessage from within the OnConnected method it works:
public override Task OnConnected()
{
Clients.All.sendMessage("Connection Initialised");
return base.OnConnected();
}
After spending some decent time to investigate the problem I have finally found the solution. Not 100% sure, but I think the problem was with using the UpdatePanel on the page. Wrapped signalR javascript code to Sys.Application.add_load instead of using jQuery's $(function () { and it started working.
The reason I mentioned that I am not 100% sure is that the UpdatePanel with the ScriptManager has been removed multiple times giving no results before posting the question.
Related
I have a page "GetData.cshtml" where I need to fill up some textbox data and send to the controller method. I am using jquery to send data to the controller method.
//GetData.cshtml
$(document).ready(function () {
$('#btn_sbmt_recommendation').click(function () {
$.post("/RegistrationModels/Registration_card",
{
firm_id: $('#id_reg_id').val(),
amount: $('#id_amount').val()
});
console.log("job done....");
});
})
While debugging the app, the controller method is called successfully.
public ActionResult Registration_card(string reg_id, string amount)
{
try
{
// code block
return View(updated_firm);
}
catch (Exception ex) { throw; }
}
As my requirement, I want to display the data in Registration_card.cshtml page, but it is not redirecting to the page.
The console message console.log("job done...."); in the jquery block is showing. It means the page is again back to GetData.cshtml. Is it due to using jquery to call controller method?
How can I go to page Registration_card.cshtml after calling the controller method Registration_card via jquery.
I also tried with the below code, but it is also not working.
public ActionResult Registration_card(string firm_id, string ward_calani_num, string amount)
{
try
{
// code block
return RedirectToAction("Registration_card", updated_firm);
}
catch (Exception ex) { throw; }
}
According to your question, it seems you want to redirect/go to the Registration_card.cshtm from GetData.cshtml by taking some data from the GetData.cshtml to the Registration_card ActionMethod which will actually show the Registration_card.cshtm.
If the above scenario is true, then you do not need to Ajax Post request as your ActionMethod is HttpGet as you do not specify it is as HttpPost. So the workaround can be something like the below code.
$(document).ready(function () {
$('#btn_sbmt_recommendation').click(function () {
var id_reg_id=$('#id_reg_id').val();
var id_amount=$('#id_amount').val();
location.href=`/RegistrationModels/Registration_card?reg_id=${id_reg_id}&amount=${id_amount}`;
//$.post("/RegistrationModels/Registration_card",
// {
// firm_id: $('#id_reg_id').val(),
// amount: $('#id_amount').val()
// });
//console.log("job done....");
});
})
If want to redirect page you should use javascript or jquery because when you use jquery then controller not working for redirect.
So I am trying to implement SignalR in a project my code is as follows:
MtHub.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace HaldanMT
{
public class MtHub : Hub
{
public void RemoveResource(string message)
{
Clients.All.RemoveResource(message);
}
}
}
custom.js:
$(document).ready(function () {
$.connection.mtHub.client.removeResource = function (message) { // This is the client listener that will fire once the server invokes the message. This is not taking place
console.log("finished");
RemoveResource(message); // Function to be invoked once the signalR message has been received from the server
}
});
function RemoveSelf(message){
$.connection.hub.start()
.done(function () {
console.log("Fire SignalR");
$.connection.mtHub.server.removeResource(message); // Invoke the SingalR server function that would in turn invoke the client listening function
})
.fail(function () {
console.log("Error With SignalR");
});
}
function RemoveResource(message){
alert(message); // Display message
}
HTML:
<button onclick="RemoveSelf('This is a message');">Click Me</button>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.1.js"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script src="~/Scripts/custom.js" type="text/javascript"></script>
Now...The correct function is fired on the button click event but the response to the client does not get invoked. If I place the SignalR invoking js function within the document ready surrounded by the onclick event of the button it works just fine. But I require the SignalR invoking js function to be fired in the function RemoveSelf(message) as other things need to take place within my code.
So my question is: Does SignalR require the server side code to be invoked via a element listener, and not within a standard function. Most examples I find are using jquery event based listeners and not a traditional function.
Thank you in advance.
The SignalR Server side code does not require invocation via element listener, but that's kind of a double-edge sword because JavaScript essentially works off events.
Your code should work exactly as it sits, but here's my code exactly and it works 100% (I don't see really many differences between our code. Could just be a typo somewhere) :
Hub
[HubName("mtHub")]
public class MtHub : Hub
{
public void RemoveResource()
{
Clients.All.RemoveResource("yo");
}
}
JavaScript (this is code inside client-side.js)
$(function() {
$.connection.mtHub.client.removeResource = function () {
alert("see it worked");
}
});
var CallIt = function() {
var connection = $.connection.mtHub;
$.connection.hub.start().done(function () {
alert("connected");
connection.server.removeResource().done(function () {
console.log("hi");
});
});
}
HTML
<h2 onclick="CallIt()">Fun Stuff</h2>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<script src="~/Scripts/jquery.signalR-2.2.1.js"></script>
<script src="~/signalr/hubs"></script>
<script src="~/Scripts/client-side.js"></script>
If this doesn't work, can you let me know what errors you get?
Your client methods have the wrong casing for the method names, you are using "RemoveResource" and they should be "removeResource"
This is incorrect:
function RemoveResource(message){
alert(message); // Display message
}
This should fix the problem:
function removeResource(message){
alert(message); // Display message
}
I building a mobile views for my website and i am still in process of creating them. i want to test how it would look on live device. so i would like to disable the .mobile files and below i tired running some scripts to disable but no luck.
<script>$(function () {
$('html').find('*').attr('data-role', 'none');
});
</script>
<script>$(document).ready(function () {
// disable ajax nav
$.mobile.ajaxEnabled = false;
});
</script>
Maybe these is a question for the developers but if any one can point me in the right direction.
You need to disable auto-initialization $.mobile.autoInitializePage of jQuery Mobile framework once mobileinit event is fired. Add the below code after jQuery (core) library and before jQuery Mobile in head.
<script src="jquery.js"></script>
<script>
$(document).on('mobileinit', function () {
$.mobile.autoInitializePage = false;
});
</script>
<script src="jquery-mobile.js"></srcipt>
To manually initialize jQuery Mobile, you need to call $.mobile.initializePage();
hey Omar thanx for the help but i found it how disable it [blog.mirajavora.com/overriding-browser-capabilities-in-asp.net]
public class BrowserCapabilitiesSwitcherFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var switchParameter = f filterContext.RequestContext.HttpContext.Request.QueryString["switch"];
if(string.IsNullOrEmpty(switchParameter))
return;
var browserOverride = BrowserOverride.Desktop;
if(Enum.TryParse(switchParameter, true, out browserOverride))
{
//switch between BrowserOverride.Desktop / BrowserOverride.Mobile
filterContext.RequestContext.HttpContext.SetOverriddenBrowser(browserOverride);
}
else
{
//set the user-agent string
filterContext.RequestContext.HttpContext.SetOverriddenBrowser(switchParameter);
}
}
}
I don't work much with javascript, but I'm trying to get dragging working with the Modal boxes from the GWT Bootstrap project. So I have a GWT project, I have an entrypoint module. I add a Modal dialog box to the document and give it a title. Then I try to call the draggable method from the jQuery UI framework on that widget. Since it's just a div, everything should work.
My first problem was that the stuff in the <script> tags was getting run before the element ever got added to the DOM. So I moved it into the notifyHostPage() function and hoped to call it from there. But jQuery UI seems to unload itself from the page after it exits the tag the first time. I've included the code to show what I've tried, and the output it results in. This is really crazy.
I've tried moving the <scripts> to below the nocache.js file, I've tried just putting them in the gwt.xml, but because of super dev mode or whatever it won't let me. I've tried using document.write() to add the scripts inside the notifyHostPage() function. I've tried just adding the class ui-draggable to the modal dialog, but because jQuery UI disappears that doesn't work either. I've tried using local resources and a CDN. I'm kind of at my wits end.
module.html
<script type="text/javascript" language="javascript" src="module/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" language="javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.js"></script>
<script type="text/javascript" language="javascript" src="module/module.nocache.js"></script>
<script type="text/javascript">
$(function() {
if (jQuery.ui) {
// UI loaded
console.log("yes");
console.log(jQuery.ui);
} else {
console.log("no");
}
});
function startDragging() {
if (jQuery.ui) {
// UI loaded
console.log("yes");
console.log(jQuery.ui);
} else {
console.log("no");
}
$("#myModal").draggable({
handle: ".modal-header"
});
};
</script>
Entrypoint module
public native void notifyHostPage() /*-{
if ($wnd.jQuery.ui) {
// UI loaded
console.log("yes");
console.log(jQuery.ui);
} else {
console.log("no");
}
$wnd.startDragging();
}-*/;
Output
yes
Object
accordion: function ( options, element ) {
autocomplete: function ( options, element ) {
button: function ( options, element ) {
buttonset: function ( options, element ) {
datepicker: Object
ddmanager: Object
dialog: function ( options, element ) {
draggable: function ( options, element ) {
droppable: function ( options, element ) {
hasScroll: function ( el, a ) {
ie: false
intersect: function (draggable, droppable, toleranceMode) {
keyCode: Object
menu: function ( options, element ) {
mouse: function ( options, element ) {
plugin: Object
position: Object
progressbar: function ( options, element ) {
resizable: function ( options, element ) {
selectable: function ( options, element ) {
slider: function ( options, element ) {
sortable: function ( options, element ) {
spinner: function ( options, element ) {
tabs: function ( options, element ) {
tooltip: function ( options, element ) {
version: "1.10.1"
__proto__: Object
no
no
Final Solution:
I've updated my files as so:
entrypoint.java
public class RecondoHISModern implements EntryPoint {
final RecondoHISServletInterfaceAsync recondoHIS = GWT.create(RecondoHISServletInterface.class);
public void onModuleLoad() {
loadScripts();
}
private void loadScripts() {
// ScriptInjector.fromString("public/js/jquery-ui-1.10.4.custom.min.js").inject();
// ScriptInjector.fromString("public/js/nprogress.js").inject();
List<String> scripts = Arrays.asList( //"//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.js",
"//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js",
"//cdnjs.cloudflare.com/ajax/libs/nprogress/0.1.2/nprogress.min.js");
injectScriptsInOrder(scripts);
}
private void injectScriptsInOrder(final List<String> scripts) {
if (scripts.size() > 0) {
ScriptInjector.fromUrl(scripts.get(0))
.setRemoveTag(false)
.setWindow(ScriptInjector.TOP_WINDOW)
.setCallback(new Callback<Void, Exception>() {
#Override
public void onFailure(Exception reason) {
GWT.log("The script " + scripts.get(0) + " did not install correctly");
}
#Override
public void onSuccess(Void result) {
GWT.log("The script " + scripts.get(0) + " installed correctly");
injectScriptsInOrder(scripts.subList(1, scripts.size()));
}
}).inject();
} else {
createModal();
}
}
public void createModal() {
Modal modal = new Modal();
modal.setTitle("Java Created Modal");
modal.setClosable(true);
ModalBody modalBody = new ModalBody();
modalBody.add(new Span("Create in Java Code!"));
ModalFooter modalFooter = new ModalFooter();
modal.add(modalBody);
modal.add(modalFooter);
modal.setId("myModal");
modal.show();
draggable();
}
private native void draggable() /*-{
$wnd.jQuery("#myModal").draggable({
handle: ".modal-header"
});
}-*/;
}
At first it was crashing at this function in modal.show();
private native void modal(final Element e, final String arg) /*-{
$wnd.jQuery(e).modal(arg);
}-*/;
But then I realized that maybe I shouldn't be loading jQuery twice, so I removed jQuery from the ScriptInjector list and everything started working fine!
You shouldn't load JS dependencies via <script> tags in your HTML file.
Either specify them in your module .gwt.xml file via <script> or better use ScriptInjector for compatibility with SuperDevMode.
Create an EntryPoint for your module and inject the JS dependencies there. See how we did it in our GwtBootstrap3 project. Since you're using GwtBootstrap3 you don't need to inject jQuery. This will already be done by GwtBootstrap3. Just inject jQuery UI and make sure to specify your <entry-point> after all <inherits>.
Once this is resolved you should be able to run something like this from your presenter:
private native void draggable() /*-{
var $modal = $wnd.jQuery("#myModal");
$modal.draggable(...);
}-*/;
This link explains how to handle it on the server side via the ASPxGridView.AfterPerformCallback event:
http://www.devexpress.com/Support/Center/p/Q274366.aspx
How can I handle it on the client side?
I am working on a custom server control and I have this client side function on my control:
applyFilterToGridView: function () {
this.theGridView.ApplyFilter(this.filterCondition);
this.filterAppliedEvent();
}
Because ApplyFilter does a callback, this.filterAppliedEvent() is not called at the right time which should be after the filtering is complete. this.filterAppliedEvent() is a client side function.
This event is fired after the filter is applied:
protected void theGridView_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
{
if (e.CallbackName == "APPLYFILTER")
{
}
}
Is there some way to to tell the client to call filterAppliedEvent from the AfterPerformCallback event?
I would prefer to be able to run this.filterAppliedEvent() after AfterPerformCallback on the client side if possible.
Thanks in advance.
EDIT ( Solution thanks to Filip ):
C#:
protected void theGridView_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
{
if (e.CallbackName == "APPLYFILTER")
{
ASPxGridView gv = sender as ASPxGridView;
gv.JSProperties["cp_FilterApplied"] = "true";
gv.JSProperties["cp_VisibleRowCount"] = gv.VisibleRowCount;
}
}
theGridView.ClientSideEvents.EndCallback = "function(s,e){"theGridView.theGridView_OnEndCallback(s, e);}";
JS:
theGridView_OnEndCallback: function (s, e) {
if (s.cp_FilterApplied) {
if (s.cp_FilterApplied.indexOf('true') != -1) {
this.adjustGridViewSize();/*Uses visible row count.*/
delete s.cp_FilterApplied;
}
}
}
In theGridView_AfterPerformCallback add entry to JSProperties collection, e.g. cp_FilterApplied.
Add EndCallback client side event handler.
In EndCallback handler execute this.filterAppliedEvent() if cp_FilterApplied exists.
Delete that property so that subsequent callback doesn't execute filterAppliedEvent method.
Look at my answer to this question for code example.
It's really the same problem, just set js property in theGridView_AfterPerformCallback instead of ASPxGridView1_RowUpdated and adjust names/js code to your needs.