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);
});
Related
I'm trying to make an ajax call in Prestashop Admin:
I created a module without a config page. It just add a button in some backoffice page, I'm trying to make an ajax call to my module file without success.
Making an ajax call in frontend is working (I added an ajax.php file in my modules/mymodule/controller/front/ directory), I tried to do the same thing for admin but it's not working at all.
What I've done:
loading the js file from actionAdminControllerSetMedia is ok
adding this in the composer.json file:
"autoload": {
"psr-4": {
"MyModule\\Controller\\": "controllers/admin/"
},
"config": {
"prepend-autoloader": false
},
created the controllers/admin/ajax.php file with this code (based on this documentation code):
namespace MyModule\Controller;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
class DemoController extends FrameworkBundleAdminController
{
public $auth = false;
public $ssl = true;
public $ajax = true;
public $errors = false;
public $message;
public function __construct()
{
parent::__construct();
}
public function initContent()
{
parent::initContent();
}
public function postProcess()
{
PrestaShopLogger::addLog("MODULE CONTROLLER OK ", 1);
}
public function displayAjax()
{
$this->ajaxDie(json_encode(array('success'=> !$this->errors, 'message' => $this->message)));
}
}
Then I tried to call the ajax from different way in js but never worked (the post query return is a message from prestashop "page not found" with http 200 response.
the doc isn't very helpful and I only find old messages/ways to do (from Prestashop 1.7.5 I'd be able to create a custom Admin controller but it doesn't work), can someone explain me the steps to follow?
thanks
Assuming it is for a PS1.7+ module, using Symphony:
Declare a link in a method of your admin controller (src/Controller/Admin) e.g
$adminLink = $this->generateUrl()
and return in with:
return $this->render
In your views/js/back.js"
$.ajax({
url: adminLink,
type: 'POST',
async: false,
data: {
},
success: (data) => {
}
});
Note: check the generateUrl and render functions for the necessary arguments.
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 ()
This question already has answers here:
Example AJAX call back to an ASP.NET Core Razor Page
(8 answers)
Closed 5 years ago.
i am trying to get some data from Razor Pages in ASP.NET Core 2.0.
But the problem is that it does not returns any data.
I also tried debugging it, it does not fire that method (OnGetProducts) at all.
The model Index.cshtml.cs:
private IProductRepository _productRepository;
public IndexModel(IProductRepository repository)
{
_productRepository = repository;
}
public void OnGet()
{
}
public IActionResult OnGetProducts(int page)
{
var model = _productRepository.GetProducts().Skip(page * 10).Take(10);
return new JsonResult(model);
}
the razor page Index.cshtml
<div id="products">
</div>
#section scripts{
<script>
$(function () {
getProducts(0);
});
var isInitialized = false;
function getProducts(page) {
$.ajax({
type: 'GET',
url: "Products",
contentType: "application/json",
dataType: "json",
data: {
handler: 'Products',
page: page
},
success: function (datas) {
console.log(datas);
}
});
}
</script>
}
p.s. this page in in folder Pages/Products/Index.cshtml(.cs)
I usually use razor functions to generate URLs instead of hard coding them in js. If your action is not even being triggered, assuming that you are not accidentally in release mode, it is because the URL doesn't point to the right location. First of all set js variables in razor something like this:
var productsURL = #Url.Context("~/products");
Also run yourdomain/products in your browser and if you get a 404.
Alternatively I use this function to directly use c# objects in js:
public static IHtmlContent ToJS(this IHtmlHelper htmlHelper, object obj)
=> htmlHelper.Raw(JsonConvert.SerializeObject(obj));
With this function created in a static class, you can also create a js object directly something like this:
<script>
var products = #Html.ToJS(repository.GetProducts().Skip(page * 10).Take(10));
</script>
Of course this will only create the object in page load, if you want it to change after page load, you can consider creating a partial view via ajax. Also note that the second alternative will be slower than the first for ajax.
I have a RPI running Windows 10 IoT. Using this link I managed to get a web api running that says "Hello world", but now I'm stuck.
What I want is a web page with a few buttons that I can put some code behind to control stuff.
I have searched to find a simple button -> action example but all I found was way over the top (for my purpose) MVC examples. I just need something simple but I can't figure it out.
Hope someone can point me in the right direction.
You can choose jQuery+ajax to excute behind code, for example :
Razor Page(Contact.cshtml)
<input type="button" value="Button1" id="button1" />
<input type="button" value="Button2" id="button2" />
JavaScript Code
$(function () {
$("#button1").click(function () {
$.post("/Sample/Action1", function (result) {
alert("Click Button1,Action1 Success!");
});
});
$("#button2").click(function () {
$.post("/Sample/Action2", function (result) {
alert("Click Button2,Action2 Success!");
});
});
});
Behind Code(SampleController.cs)
[HttpPost]
public JsonResult Action1()
{
//action 1 ...
return Json(new { Success = true });
}
[HttpPost]
public JsonResult Action2()
{
//action 2 ...
return Json(new { Success = true });
}
Before that, you should make sure jquery library is included in your page.
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);
}