【问题标题】:Radio button not showing as checked单选按钮未显示为选中
【发布时间】:2013-04-26 17:58:01
【问题描述】:

我正在使用带有 MVC 4 的 Knockout。我的 cshtml 是:

...
<span>@Html.RadioButtonFor(m => m.isActive, true, new { @class = "statusRadioButton", data_bind = "checked: isActive" })</span>
<span>@Html.RadioButtonFor(m => m.isActive, false, new { @class = "statusRadioButton", data_bind = "checked: isActive" })</span>
...

我的哥:

...
self.isActive = ko.observable(product.isActive);
...

正确更新数据库,但它在页面加载时未显示任何已选中的单选按钮。我也尝试使用 checked = "checked" html 属性,但它也不起作用。有什么建议吗?

【问题讨论】:

  • product.isActive 是否可观察?

标签: asp.net-mvc-4 razor knockout.js radio-button html-helper


【解决方案1】:

你的 product.isActive 是可观察的吗?如果是这样,那么您将需要像 product.isActive() 那样执行 observable

通过像self.isActive = ko.observable(product.isActive()); 这样的初始化,您只需设置一次。

试着把它变成可观察的,比如:

self.isActive = ko.computed(function() {
                                return product.isActive();
                             });

编辑: 尝试将您的单选按钮更改为:

<span>@Html.RadioButtonFor(m => m.isActive, true, new { @class = "statusRadioButton", data_bind = "checked: isActive", value="true" })</span>
<span>@Html.RadioButtonFor(m => m.isActive, false, new { @class = "statusRadioButton", data_bind = "checked: isActive", value="false" })</span>

并编写您的 observable 以使用 isActive 中的布尔值作为字符串。

self.isActive = ko.computed(function() {
                                return product.isActive.toString();
                             });

【讨论】:

  • 我试过了,它会抛出错误,我认为这是因为 isActive 是一个布尔值,而不是一个函数。所以我更改了您的代码以返回 product.isActive; ,现在它没有中断,但问题仍然存在。
  • 来自 KO 文档:'对于单选按钮,当且仅当参数值等于单选按钮节点的 value 属性时,KO 才会设置要检查的元素。它们的工作方式与复选框不同。查看我的编辑
  • 还是什么都没有。我什么都试过了。仍然会更新数据库,但在页面加载时不显示选中的单选按钮。
  • 已解决。我改了:self.isActive = ko.observable("True");
猜你喜欢
  • 2016-12-30
  • 2014-08-22
  • 2019-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 2021-06-10
相关资源
最近更新 更多