我有一个包含以下对象的JS数组:
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);
};
}
当数组发布到我的MVC控制器时,如果数组为空,它可以正常工作。如果数组中有一个对象,它就会崩溃。
是否存在问题,因为我的json对象包含函数?
干杯,
詹姆斯
答案 0 :(得分:1)
函数不能被JSON序列化。您不应该尝试序列化此类对象。从您的代码看起来您已经将一些skillModelAdapter
对象传递给SkillModel
构造函数,该构造函数看起来很适合JSON序列化:
例如:
var skillModelAdapters = [
{ SkillId: 1, SkillName: 'skill 1', Proficiency: 1 },
{ SkillId: 2, SkillName: 'skill 2', Proficiency: 1 },
{ SkillId: 3, SkillName: 'skill 3', Proficiency: 3 },
{ SkillId: 4, SkillName: 'skill 4', Proficiency: 2 }
];
然后:
$.ajax({
url: '@Url.Action("SomeAction")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(skillModelAdapters),
success: function(result) {
}
});
在服务器端,您将拥有一个视图模型:
public class SkillViewModel
{
public int SkillId { get; set; }
public string SkillName { get; set; }
public int Proficiency { get; set; }
}
和相应的控制器操作:
[HttpPost]
public ActionResult SomeAction(IEnumerable<SkillViewModel> skills)
{
...
}