Having these ASP.NET MVC view models:
public class User
{
public string Name { get; set; }
public LabeledEmail LabeledEmail { get; set; }
}
public class LabeledEmail
{
public IList<ContactLabel> Labels;
public IList<ContactEmail> Emails;
}
and Knockout view model like this:
<script type="text/javascript">
$(function() {
ko.applyBindings(viewModel);
$("#profileEditorForm").validate({
submitHandler: function(form) {
if (viewModel.save())
window.location.href = "/";
return false;
}
});
});
var viewModel = {
Name: ko.observable("@Model.Name"),
EmailLabels: ko.observableArray(@Html.Json(Model.LabeledEmail.Labels.Select(l => l.Name)) || []),
Emails: ko.observableArray(@Html.Json(Model.LabeledEmail.Emails) || []),
addEmail: function() {
viewModel.Emails.push(@Html.Json(new ContactEmail()));
},
removeEmail: function(eml) {
viewModel.Emails.remove(eml);
},
saveFailed: ko.observable(false),
// Returns true if successful
save: function() {
var saveSuccess = false;
viewModel.saveFailed(false);
jQuery.ajax({
type: "POST",
url: "@Url.Action("MyAction", "MyController")",
data: ko.toJSON(viewModel),
dataType: "json",
contentType: "application/json",
success: function(returnedData) {
saveSuccess = returnedData.Success || false;
viewModel.saveFailed(!saveSuccess);
},
async: false
});
return saveSuccess;
}
};
</script>
What posts back properly to controller is User.Name
, but User.LabeledEmail
is empty.
I have to flatten the model the way I do in order to be able to use lists separately elsewhere.
I know for fact that viewModel.Emails is populated properly while saving, but User.LabeledEmails is somehow returns null.
It basically comes down to assigning Model.LabeledEmail.Emails
the viewModel.Emails
and the deal will be solved, seems, but I don't know how and cannot find any appropriate examples.
- What is the mistake that I make and
- How to do it properly?
Thank you in advance.