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.
You will want to remove the
()fromvalue: comments().For a read/write binding like
valueit 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.