将复杂的AJAX发布到MVC控制器
我正在尝试使用Ajax保存在浏览器中创建的场景。数据结构非常简单。主要对象是场景
,子对象是cente> sceneObject
的类型。
这是我的场景
模型类:
public class Scene
{
[Key]
public int id { get; set; }
[Required]
public string name { get; set; };
public virtual ICollection<SceneItem> sceneItems { get; set; }
}
这是我的staceItem
模型类:
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; }
}
这是我的ajax代码:
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);
});
当我在ASP的调试窗口中执行此AJAX调用时。 NET MVC应用程序,我可以看到所有字段均已填充,除了
virtual public Scene scene { get; set; }
我的staceItem
模型。这使modelState.isvalid
在我的控制器中返回false。
我该怎么做才能以一种可以在单个ajax命令中的sceneItem
对象发布场景
对象的方式来完成此工作。 并使用实体框架将其保存到我的数据库中?
非常感谢您的任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将所需的字段名称添加到您的Ajax JSON
add a required field name to your ajax json