How can send parameters and data from controller to SignalR hub in ASP.NET MVC?

62 Views Asked by At

I use ASP.NET MVC. I want to send data from a controller to hub for sending to clients. I wrote this code in the controller:

public class SampleController : Controller
{
    private readonly IHubContext<silgramHubs> _hubContext;

    public SampleController(IHubContext<silgramHubs> hubContext)
    {
        _hubContext = hubContext;
    }

    public SampleController()
    {
    }

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Save(long id = 0, string note = "")
    {
        NumberViewModel ml = new NumberViewModel { Iid = id, INote = note };
        return RedirectToAction("OneMessage", ml);
    }

    public ActionResult OneMessage(NumberViewModel ml)
    {
        var Iid = (int)ml.Iid;
        var Note = ml.INote;

        _hubContext.Clients.All.sendPartialViewHtmlToClients(Iid, Note);

        return PartialView(ml);
    }
}

This is the code related to my hub:

using System.Web.Mvc;
using System.Text;
using System.IO;
using testproject.Controllers;

namespace testproject.Hubs
{
    public class SilgramHubs : Hub
    {
        public void sendPartialViewHtmlToClients(int id, string note)
        {
            Clients.All.addNewMessage(id, note);
        }
    }
}

StartUp.cs:

using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;
using Microsoft.AspNet.SignalR.SqlServer;
using Microsoft.Owin.Cors;

[assembly: OwinStartup(typeof(SadeMvc.Startup))]

namespace SadeMvc
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR("/signalr", new HubConfiguration
            {
                EnableJSONP = true, // if needed
                EnableDetailedErrors = true // if needed
            });

            app.UseCors(CorsOptions.AllowAll);

            app.MapSignalR();

        }
    }
}

And this is my client-side scripts to connect to the hub and receive messages:

$(function () {
    var chat = $.connection.chatHubs;

    chat.client.addNewMessage = function (id, note) {
        console.log("Received message:", id, note);
    };

    $.connection.hub.start().done(function () {
        console.log("SignalR hub connected");
    });
});

Unfortunately, the operator in the following line exits without any error.

_hubContext.Clients.All.sendPartialViewHtmlToClients( Iid, Note);

I want to send parameters from the controller to the hub in ASP.NET MVC. Please guide me how to do this.

1

There are 1 best solutions below

0
Mehregan On

I have an alternative suggestion to get the hubContext. you can create hubcontext as follow:

var hubcontext = GlobalHost.ConnectionManager.GetHubContext<SilgramHubs>(); 
hubcontext.Client.All.sendPartialViewHtmlToClients(Iid, Note); 

I think this work.