我使用ScottGu在线提供的NerdDinner教程创建了一个类似NerdDinner的应用程序。我想将SignalR添加到我的应用程序中,这样每次创建新的晚餐时,主页上显示的晚餐价值都应该更新。
我的HomeController中有一个create方法
[HttpPost]
public ActionResult Create(Dinner dinner)
{
if (ModelState.IsValid)
{
nerdDinners.Dinners.Add(dinner);
nerdDinners.SaveChanges();
}
return RedirectToAction("Index");
}
我的Hub课程如下:
[HubName("DinnerHub")]
public class NewDinnerHub : Hub
{
int dinnerCount = 0;
NerdDinners.Models.NerdDinners nerdDinners = new NerdDinners.Models.NerdDinners();
public void SendDinnerNumber(int no_of_dinners)
{
var dinners = from d in nerdDinners.Dinners
select d;
dinnerCount = dinners.ToList().Count();
no_of_dinners = dinnerCount;
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NewDinnerHub>();
context.Clients.All.getDinnerNumber(this.Context.ConnectionId, no_of_dinners);
}
}
这是我的index.cshtml
@model IEnumerable<NerdDinners.Models.Dinner>
<h2>Index</h2>
<h1>Upcoming Dinners</h1>
<ul>
@foreach(var d in Model) {
<li>
@Html.DisplayFor(modelItem => d.Title)
@Html.DisplayFor(modelItem => d.EventDate)
</li>
}
</ul>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<p>
@Html.Label("Number_of_Dinners","Number of Dinners : ") <label id="No_of_Dinners" />
</p>
<table>
<tr>
<th>
Title
</th>
<th>
EventDate
</th>
<th>
Address
</th>
<th>
HostedBy
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.EventDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.HostedBy)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.DinnerID }) |
@Html.ActionLink("Details", "Details", new { id=item.DinnerID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.DinnerID })
</td>
</tr>
}
</table>
我的index.cshtml里面的javascript也在
之下<script>
$(function () {
var hub = $.connection.DinnerHub;
$No_of_Dinners = $("#No_of_Dinners");
hub.client.getDinnerNumber = function (connectionId, no_of_dinners) {
$No_of_Dinners.text = no_of_dinners;
};
$.connection.hub.start().done(function () {
hub.server.sendDinnerNumber($No_of_Dinners);
});
});
</script>
<script src="../../Scripts/jquery-1.7.1.js"></script>
<script src="../../Scripts/jquery-ui-1.8.20.js"></script>
<script src="../../Scripts/jquery.signalR-1.0.1.js"></script>
<script src="/signalr/hubs"></script>
我不确定出了什么问题。每当添加新的晚餐时,我都需要用数据库中的晚餐数量更新我的'No_of_Dinners'标签。此外,我正在使用.Net MVC4,我不想将我的模式更改为MVVM。我在网上看到的所有例子都是MVVM。
提前致谢。
答案 0 :(得分:1)
我解决了这个问题。我没有正常工作,因为我没有RegisterRoutes()上面的Route.MapHubs()方法。另外,我不得不从_Layout.cshtml中删除bundles / jquery