2015-04-30 23 views
0

我被困在從我的web應用程序顯示來自其他客戶端的響應消息。到目前爲止我做了什麼?爲模型項目上的更改創建信號R回調

的HomeController

private static IHubProxy _hub; 
private static HubConnection _connection; 
private string url = @"http://server:port/"; 
private static Model model = new Model(); 

public ActionResult Login() 
{ 
     _connection = new HubConnection(url); 
     _hub = _connection.CreateHubProxy("ServerHub"); 

     _hub.On<string>("ReturnSendMessage", ShowMessage); 
     _hub.On<string>("ReturnSignInMessage", ShowMessage); 

     return View(); 
} 

[HttpPost] 
public ActionResult Login(FormCollection collection) 
{ 
     model.NickName = collection.Get("NickName"); 

     _connection.Start().Wait(); 
     _hub.Invoke("SignIn", model.NickName, true).Wait(); 

     return RedirectToAction("Chat", "Home"); 
} 

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

[HttpPost] 
public ActionResult Chat(FormCollection collection) 
{ 
     model.Message = collection.Get("Message"); 
     _hub.Invoke("SendMessage", model.NickName, model.Message).Wait(); 

     return View(); 
} 

public ActionResult ChatPartialView() 
{ 
     return PartialView("ChatPartialView"); 
} 

視圖 - ChatPartialView

@model DxComWithMe.Models.Model 

<div> 
    <h3>Chat history</h3> 

    @if (Model != null) 
    { 
     foreach (var item in Model.Messages) 
     { 
      <strong>@item</strong> 
      <br> 
     } 
    } 
</div> 

一切工作正常,只要我刷新頁面自己。但我想實現一種機制,在例如Model.Messages已更改。是否有無論如何做,或者我必須依靠這種方法(javascript ...)來實現回調功能:http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc

回答

0

您在MVC應用程序中使用.NET客戶端,不會工作(不是你打算的方式)。您需要使用JavaScript客戶端庫

你叫從服務器上的客戶端樞紐方法這樣

GlobalHost.ConnectionManager.GetHubContext<ServerHub>() 
    .Clients.All.SendMessage(...); 

編輯:是否有參與這個兩個服務器?

+0

我認爲是這樣的:/我只是想在我的WPF客戶端。不,只有一個處理請求的服務器(Windows服務)。 – Insight

0

在我看來,你不應該在你的控制器中處理Hub動作,而是在一個專用的Hub類中。 Signalr依賴於客戶端的JavaScript,並且必須使用JavaScript函數處理客戶端中的中心事件。

例如,您可以使用knockout來綁定與您的集線器交互的js模型上的dom元素。

+0

我明白了。 JavaScript將是方式。我只是想在我的wpf客戶端中進行組織,但似乎並不打算這麼做。然後切換到JavaScript。 – Insight