是否可以在 View 中创建对象并通过 ajax 将其发送到 Controller ?
使用
$.ajax({
type: "POST", etc....
???
我想发送我在 View 中收到的类型的对象
@model Project1.ViewModels.ModelSample
最佳答案
这是可能的
这是完全(并且很容易)可能的。
复杂的对象呢?
@xixonia 提供了您可能需要的所有信息。但是这些示例相当基本,如果您有某种复杂的对象,可能无法提供信息,例如:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public Person Spouse { get; set; }
public IList<Person> Children { get; set; }
}
任何在其树中具有多于一层属性的对象都被视为复杂对象。在这种情况下,使用 @xixonia 提供的技术将无法正常工作。
因此,如果您也想使用这种场景,我建议您阅读 this blog post它详细描述了整个问题,并提供了一个相当简单的 jQuery 插件,它可以将甚至复杂的对象发送到 Asp.net MVC Controller 操作,这些操作将模型绑定(bind)到您的任何复杂的强类型。
同一博客上的其他帖子也可能会有所帮助:
IList<T>
action parameters (or within complex type parameters) 如果您将在 Asp.net MVC 中使用 Ajax,您会发现这些帖子非常有用,并且在遇到此类问题时可以节省您大量的开发时间。
关于asp.net - 将 View 模型从 ajax 发送到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5724836/