Reputation: 12915
Throughout my app, I'd like to use Razor for all functionality related to Reading, and leverage knockoutJS and AJAX for CUD operations.
In my profile view, I've done the following:
<div>
<h4>About Me</h4>
<!-- ko if: !isEditingAboutMe() -->
<p>@Model.User.AboutMe</p>
@if (Model.CurrentUserCanEdit)
{
<a data-bind="click: editAboutMe">edit</a>
}
<!-- /ko -->
<!-- ko if: isEditingAboutMe() -->
@Html.TextBoxFor(model => model.User.AboutMe, new { data_bind = "value: aboutMe" })
<a data-bind="click: saveAboutMe">save</a>
<a data-bind="click: cancelAboutMe">cancel</a>
<!-- /ko -->
</div>
This way search engines can at least crawl the content, and users with javascript enabled can perform CUD operations.
My problem above is that - using AJAX, if I click "save", how to I bind the new value to the Razor model (fourth line down)?
Corresponding JS:
function ProfileVm() {
var self = this;
self.aboutMe = ko.observable();
self.saveAboutMe = function() {
// AJAX call, after success close the field
self.isEditingAboutMe(false);
};
self.cancelAboutMe = function() {
// just for testing, would revert the value in practice
self.isEditingAboutMe(false);
};
self.isEditingAboutMe = ko.observable(false);
self.editAboutMe = function() {
self.isEditingAboutMe(true);
};
}
$(document).ready(function () {
ko.applyBindings(new ProfileVm());
})
Also - feedback regarding the "properness" of this approach is welcome.
Upvotes: 2
Views: 4563
Reputation: 49095
It is unclear why you're using Knockout only for write operations (CUD) and not also for read. doing so can solve your problem automatically:
Instead of:
<p>@Model.User.AboutMe</p>
You should follow the Knockout way, so you'll have a two-way model binding:
<p data-bind="text: aboutMe()"></p>
Now, once the aboutMe
field is updated, Knockout will make sure the data within the <p>
element will be updated as well.
Edit:
Since you want search engines visibility of the user details, you can try this:
<p data-bind="text: aboutMe()">@Model.User.AboutMe</p>
This way, simple retrieval of the server response (without Script invocation) would indeed include the desired text, but once Knockout will kick-in (almost immediately) you'll still have full Model Binding with fresh data.
Upvotes: 3