'Post complex ajax to MVC controller

I'm trying to save a scene created in a browser using Ajax. The data structure is pretty simple. Primary object is Scene and child objects are type of SceneObject.

Here is my Scene model class:

public class Scene
{
    [Key]
    public int id { get; set; }
    [Required]
    public string name { get; set; };
    public virtual ICollection<SceneItem> sceneItems { get; set; }
}

And this is my SceneItem model class:

public class SceneItem 
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string name { get; set; }
    public float size { get; set;}
    public int sceneId { get; set; }
    virtual public Scene scene { get; set; }
}

Here is my Ajax code:

    var scene ={
                    sceneItems:[ {
                        id: 0,
                        name: "test1",
                        size: 0.35,
                        sceneID: 1
                    },
                    {
                        id: 0,
                        name: "test2",
                        size: 0.65,
                        sceneID: 1
                    }]
                }
                
                $.ajax({
                    type: "POST",
                    url: "/scene/create",
                    data: scene
                }).done(function (data) {
                    alert(data);
                });

When I execute this Ajax call, in my debug window of the ASP.NET MVC app, I can see all fields are populated except

virtual public Scene scene { get; set; }

from my SceneItem model. And that makes the ModelState.IsValid return false in my controller.

What can I do to make this work in a way that I can post a Scene object along side many SceneItem objects in a single AJAX command and pass ModelState.IsValid and save it into my database using Entity Framework ?

Thank you so much for any help.



Solution 1:[1]

add a required field name to your ajax json

var scene ={
             id: 0,
             name="name",
             sceneItems:[ 
              ... your data
              ]
            }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Serge