I’ve got a JS array of the following objects:
function SkillModel(skillModelAdapter) {
this.SkillId = skillModelAdapter.SkillId;
this.SkillName = skillModelAdapter.SkillName;
this.Proficiency = skillModelAdapter.Proficiency;
this.Element = null;
this.ProficiencyString = function () {
switch (this.Proficiency) {
case 1:
return "Beginner";
case 2:
return "Novice";
case 3:
return "Intermediate";
case 4:
return "Advanced";
default:
return "Expert";
}
};
this.CreateElement = function () {
var searchSkill = $('<div>').addClass('searchSkill').attr('skillId', this.SkillId);
var skillName = $('<span>').addClass('skillName').html(this.SkillName);
var proficiency = $('<span>').attr('proficiency', this.Proficiency).html(' (' + this.ProficiencyString() + ')');
var removeLink = $('<a href="#">').addClass('removeSkill').html('X');
searchSkill.append(skillName);
searchSkill.append(proficiency);
searchSkill.append(removeLink);
this.Element = searchSkill;
$('#SkillsContainer').append(searchSkill);
};
}
When the array is posted to my MVC controller it works fine if the array is empty. If the array has an object in it, it crashes.
Is there an issue because my json object contains functions?
Cheers,
James
Functions cannot be JSON serialized. You should not be trying to serialize such object. From your code it looks like that you already are passing some
skillModelAdapterobject to theSkillModelconstructor which looks a good candidate for JSON serializing:For example:
and then:
and on the server side you would have a view model:
and a corresponding controller action: