检测 html table Knockout/ASP.NET MVC 中的选定行

Posted

技术标签:

【中文标题】检测 html table Knockout/ASP.NET MVC 中的选定行【英文标题】:Detecting Selected Row in html table Knockout/ASP.NET MVC 【发布时间】:2013-03-04 12:42:52 【问题描述】:

我已经使用 ko.mapping.fromJS(Model) 将 ASP.NET MVC viewModel 加载到 KnockoutJS 中。

我的 viewModel 看起来像这样:

public IEnumerable<FunkyThing>funkyThings;
public FunkyThing selectedFunkyThing;

然后我在我的 html 视图中得到了一个看起来像这样的表格

<tbody data-bind="foreach: funkyThings">
    <tr>
        <td data-bind="text:name"></td>  
        <td data-bind="text:funkiness"></td>  
        <td><a href='#' title="Select Funky Thing" data-bind="click: $root.selectFunkyThing"></a>
       </td>
    </tr>
</tbody>

这张桌子一切都很好。点击 select funkything 链接愉快地调用 selectFunkyThing 函数:

    model.selectFunkyThing= function (funkyThing) 
        window.location = '@Url.Action(MVC.FunkyThingController.Index())' + "?funkyThingID=" + funkyThing.funkyThingID();

    ;

这反过来又刷新了页面。重新加载 MVC 视图模型,并用选定的 FunkyThing 填充 selectedFunkyThing,然后从 MVC 视图模型中重新读取淘汰视图模型。到目前为止一切顺利。

然后我想更新表格以突出显示所选条目。 所以我更新了 tr 行如下:

<tr data-bind="css:'selected': $root.isSelected()">

并创建了新的淘汰功能:

 model.isSelected = function (funkyThing) 
            return funkyThing.funkyThingID== model.selectedFunkyThing.funkyThingID;

        ;

但是...它不起作用。 Chrome 会抛出一个 javascript 异常,指出 FunkyThing 参数未定义。 从技术上讲,我认为我可以通过更改 MVC viewModel 以在数组中的每个 FunkyThing 上实际设置一个 isSelected 来解决它。但是我认为在 Knockout 中必须避免这样做?

【问题讨论】:

【参考方案1】:

你很接近!我添加了 ko.utils.unwrapObservable 调用,因为我敢打赌 funkyThingID 是一个可观察的,而不仅仅是一个直接的属性——你自己在你的 selectFunkyThing 函数中做了这个。你也可以执行它们。不过我喜欢 unwrap 的冗长。

model.isSelected = function (funkyThing) 
  var thisId = ko.utils.unwrapObservable(model.selectedFunkyThing.funkyThingID);
  return ko.utils.unwrapObservable(funkyThing.funkyThingID) == thisId;
;

然后在您的文档中,当 ko 解析绑定时,您实际上必须执行此函数

<tr data-bind="css:'selected': $root.isSelected($data)">

【讨论】:

如果您想在不重新加载页面的情况下动态更改选定的 funkyThing,这会失败,但您似乎不需要这样做。 太棒了,我花了几个小时试图弄清楚这一点。我认为 $data 位是我在这里遗漏的关键位。非常感谢。【参考方案2】:

这些属性不是都是可观察的,所以你需要将它们作为函数引用吗?我认为,您还需要使您的函数成为可计算的可观察对象:

model.isSelected = ko.computed(function (funkyThing) 
    return funkyThing().funkyThingID() == model.selectedFunkyThing().funkyThingID();
);

【讨论】:

以上是关于检测 html table Knockout/ASP.NET MVC 中的选定行的主要内容,如果未能解决你的问题,请参考以下文章

element-ui table根据属性合并行

在此查询中无法检测到错误

警告:将列添加到从函数返回的 data.table 时“检测到无效 .internal.selfref”

Linux sys_call_table变动检测

十八dbms_repair(用于检测,修复在表和索引上的损坏数据块)

有啥方法可以用 Laravel 检测数据库表是不是存在