已解决:
添加了新的更正代码行并注释了旧代码行。
对于使用SignalR的实时应用程序,我希望所有连接的客户端都可以实时看到用户所做的更改。
可以使用简单的文本框,但是当我使用下拉列表时:当用户选择一个项目时,我希望从下拉列表中选择的项目自动设置(自动更新)到所有连接的客户端。
Knockout.js似乎是显而易见的选择,但我认为我在订阅时遇到问题......或其他地方?
我有的:
(ASP .NET Razor)下拉列表:
//@Html.DropDownListFor(model => model.UserProfile.UserId, (SelectList)ViewBag.DDLUsersId, "Select User", new { @class = "ui-corner-all", @data_bind="value: selectedResponsible_UserId" })
@Html.DropDownListFor(model => model.UserProfile.UserId, (SelectList)ViewBag.DDLUsersId, "Select User", new { @class = "ui-corner-all", @data_bind="value: Responsible_UserId" })
( HTML ) 生成:
//<select class="ui-corner-all" data-bind="value: selectedResponsible_UserId" id="UserProfile_UserId" name="UserProfile.UserId"><option value="">Select User</option>
<select class="ui-corner-all" data-bind="value: Responsible_UserId" id="UserProfile_UserId" name="UserProfile.UserId"><option value="">Select User</option>
<option value="1">test1</option>
<option value="2">test2</option>
</select>
( JavaScript )视图模型:
function taskViewModel(id, title, Responsible_UserId, ownerViewModel)
{
this.taskId = id;
this.title = ko.observable(title);
//this.selectedResponsible_UserId = ko.observable(Responsible_UserId);
this.Responsible_UserId = ko.observable(Responsible_UserId);
this.notification = function (b) { notify = b }
var self = this;
this.title.subscribe(function (newValue)
{
ownerViewModel.updateTask(ko.toJS(self));
});
//this.selectedResponsible_UserId.subscribe(function (newValue)
this.Responsible_UserId.subscribe(function (newValue)
{
ownerViewModel.updateTask(ko.toJS(self));
});
}
( JavaScript )来自客户端的函数,它使用指定的对象从服务器端调用函数:
this.updateTask = function (task)
{
if (notify)
this.hub.server.s_Update(task);
}
( C# )来自服务器端的函数,它修改数据库中的值并从客户端为所有连接的具有指定对象的客户端调用函数:
public bool S_Update(Task updatedTask)
{
using (var context = new ToDoDbContext())
{
var oldTask = context.Tasks.FirstOrDefault(t => t.taskId == updatedTask.taskId);
if (oldTask == null)
return false;
else
{
oldTask.title = updatedTask.title;
//??? Here, value 'updatedTask.Responsible_UserId' was NULL !!!
oldTask.Responsible_UserId = updatedTask.Responsible_UserId;
context.SaveChanges();
Clients.All.C_TaskUpdated(oldTask);
return true;
}
}
}
(JavaScript)来自客户端的函数应该更新接口:
this.hub.client.C_TaskUpdated = function (t)
{
var task = ko.utils.arrayFilter(tasks(), function (value) { return value.taskId == t.taskId; })[0];
notify = false;
task.title(t.title);
//!! obvious, here was set to NULL.
//task.selectedResponsible_UserId(t.Responsible_UserId);
task.Responsible_UserId(t.Responsible_UserId);
notify = true;
};