You are mixing jQuery with Knockout. The submit is handled by jQuery. If you use Knockout, let it to handle the submit event adding to the <form>
this submit: submitShortlistForm,
:
<form id="shortlistForm" data-bind="submit: submitShortlistForm, style: { display: application.isShortlisted === false ? 'inline-block' : 'none'}, attr: {action: '@(MVC.GetLocalUrl(MVC.HireOrgJobApplication.ViewApplication(Model.CurrentOrganization.CustomUrl, Model.Job.JobKey, "xxx/ajax-shortlist")))'.replace('xxx', application.applicationKey)}" method="post" style="display:inline;">
@Html.AntiForgeryToken()
<input type="hidden" name="ApplicationKey" data-bind="attr:{ value : application.applicationKey }" />
<button type="submit" class="btn-act jui-tooltip" title="Shortlist">
<i class="fa fa-2x fa-star"></i>
</button>
</form>
Then, in your view model add this:
self.submitShortlistForm = function(){
// I think is better to use $.post() or $.ajax().
// I use the pluging because is in your question.
$('form#shortlistForm').ajaxForm(function () {
// Allways change position [0] of the observable array
self.applications()[0].isShortlisted = true;
var data = self.applications().slice(0);
self.applications([]);
self.applications(data);
});
$(this).ajaxSubmit();
}
In the Knockout submit event I bind the form with the ajaxForm
plugin, and then I submit it. I'm not sure about jQuery Plugin, I would use $.post()
or $.ajax()
.
You could find more information about Knockout submit in this link The "submit" binding.
I don't like this solution because you are removing all the content of the self.applications
observable array. Is better to use the mapping plugin and convert all application
objects (and its content) in observables. But with this approach, you should modify your ViewModel and the view.
Update 1 (19/06/2017)
If this <form>
is inside a foreach
loop, then the self.submitShortlistForm
could be this:
self.submitShortlistForm = function(application){
$('form#shortlistForm').ajaxForm(function () {
// Updates the current row element.
application.isShortlisted = true;
var data = self.applications().slice(0);
self.applications([]);
self.applications(data);
});
$(this).ajaxSubmit();
}
And the html:
<form id="shortlistForm" data-bind="submit: $root.submitShortlistForm, ...">
Hope this helps.