Knockout view model posts back to ASP.NET MVC partially - how to post back complete object?

前提是你 提交于 2019-12-09 03:16:27

Your JSON data structure should match the structure of your C# classes especially the property names. So you need send a JSON which look somewhat like this:

{
    Name: 'somename',
    LabeledEmail: {
        Labels: [ somelements ],
        Emails: [ someelements ]
    }
}

So change your data: ko.toJSON(viewModel),:

data: JSON.stringify({
   Name: viewModel.Name(),
   LabeledEmail: { 
       Labels: viewModel.EmailLabels(),
       Emails: viewModel.Emails()
   }
})

Or just use the data in the same structure on both the client and server...

As a side note: Your C# viewmodels need to have properties instead of fields in order to the MVC model binder work correctly:

public class User
{
    public string Name { get; set; }
    public LabeledEmail LabeledEmail { get; set; }
}

public class LabeledEmail
{
    public IList<ContactLabel> Labels { get; set; }
    public IList<ContactEmail> Emails { get; set; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!