当 css 绑定更新时,Textarea 会失去价值
我有一个使用 Razor 和 Knockout.js 的 ASP.NET MVC 3 视图,但其行为不符合我的预期。我有一对 标签,它们基本上是“同意”/“不同意”链接和一个用于评论的文本区域。如果用户点击“不同意”,我们会向文本区域添加一个 CSS 类,以突出显示当用户不同意时需要发表评论的事实。如果来自服务器的评论字段为
null
或 ""
(这始终是用户第一次访问该页面),则会出现问题。如果用户输入评论,然后单击“同意”或“不同意”链接,评论就会消失。如果页面首次加载时注释字段有值,则当用户单击链接时注释将保留。如果我删除更新 CSS 的数据绑定,一切都会正常。
这是所涉及代码的稍微简化的版本(我删除了 viewModel 中与页面此部分无关的部分):
<a href="#" onclick="viewModel.meetsCriteria('true'); return false;">
Agree
</a>
<a href="#" onclick="viewModel.meetsCriteria('false'); return false;">
Disagree
</a>
<textarea rows="6"
data-bind="value: comments(), css: { 'req': meetsCriteria() == 'false' }"
name="response.Comments">
</textarea>
...
var viewModel = {
meetsCriteria: ko.observable(''),
comments: ko.observable('')
};
viewModel.meetsCriteria('@Model.MeetsCriteria.ToString().ToLower()');
viewModel.comments('@Model.Comments');
对于正在发生的情况或如何修复它的任何想法,我们表示赞赏。
I have an ASP.NET MVC 3 view using Razor and Knockout.js that is not behaving the way I expect it to. I have a pair of <a>
tags that are basically 'agree'/'disagree' links and a text area for comments. If the user clicks 'disagree' we add a CSS class to the textarea to highlight the fact that comments are required when the user disagrees. The problem occurs if the comments field coming from the server is null
or or ""
, which it always is the first time the user visits the page. If the user enters comments and then clicks either of the 'agree' or 'disagree' links, the comments disappear. If the comments field has a value when the page first loads, the comments are persisted when the user clicks the links. If I remove the data-binding that updates the CSS, everything works fine.
Here's a slightly simplified version of the code involved (I've removed the parts of the viewModel that aren't related to this section of the page):
<a href="#" onclick="viewModel.meetsCriteria('true'); return false;">
Agree
</a>
<a href="#" onclick="viewModel.meetsCriteria('false'); return false;">
Disagree
</a>
<textarea rows="6"
data-bind="value: comments(), css: { 'req': meetsCriteria() == 'false' }"
name="response.Comments">
</textarea>
...
var viewModel = {
meetsCriteria: ko.observable(''),
comments: ko.observable('')
};
viewModel.meetsCriteria('@Model.MeetsCriteria.ToString().ToLower()');
viewModel.comments('@Model.Comments');
Any ideas about what's happening or how to fix it are appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要从
value: comments()
中删除()
。对于像
value
这样的读/写绑定,重要的是您要绑定实际的可观察值而不是它的值。在您的情况下,绑定接收注释可观察值的值,并且无法读取/写入实际可观察值。You will want to remove the
()
fromvalue: comments()
.For a read/write binding like
value
it is important that you are binding against the actual observable and not the value of it. In your case, the binding receives the value of the comments observable and won't be able to read/write to the actual observable.