将视图模型从 ajax 发送到控制器
是否可以在视图中创建一个对象并通过ajax将其发送到控制器?
使用
$.ajax({
type: "POST", etc....
??? 我想发送一个我在视图中收到的类型的对象
@model Project1.ViewModels.ModelSample
Is it possible to create an object in a view and send it to a controller through ajax?
using the
$.ajax({
type: "POST", etc....
???
I want to send an object of the type that I receive in the view as
@model Project1.ViewModels.ModelSample
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是可能的
这是完全(而且很容易)可能的。
那么复杂的物体呢?
@xixonia 提供了您可能需要的所有信息。但这些示例相当基本,如果您有某种复杂对象,可能无法提供信息,如下所示:
树中具有多个属性级别的任何对象都被视为复杂对象。
在这种情况下使用@xixonia 提供的技术将无法工作。因此,如果您也想使用这种场景,我建议您阅读 这篇博文详细描述了整个问题,并提供了一个相当简单的 jQuery 插件,可以将复杂的对象发送到将模型绑定的 Asp.net MVC 控制器操作给你任何复杂的东西强型。
同一博客上的其他帖子也可能会有所帮助:
IList
操作参数(或在复杂类型参数内)如果您使用 Ajax 和 Asp.net MVC,您会发现这些帖子非常有用,并且在遇到此类问题时会节省大量开发时间。
It's possible
This is perfectly (and easily) possible.
What about complex objects?
@xixonia provided all the information you may need to do so. But those examples are rather basic and may not provide information in case you have some sort of complex objects as:
Any object that has more than a single level of properties in its tree is regarded as a complex object.
Using technique provided by @xixonia will fail to work in this case.So if you'd like to also use this kind of scenario I suggest you read this blog post that describes the whole problem in detail as well as provides a rather simple jQuery plugin that makes it possible to send even complex objects to Asp.net MVC controller actions that will be model bound to your whatever complex strong type.
Other posts on the same blog may also prove to be helpful:
IList<T>
action parameters (or within complex type parameters)If you'll be using Ajax along Asp.net MVC you will find these posts very useful and will save you much of your development time when you run against such issues.
这就是它对我有用的方式:
This is the way it worked for me:
绝对地。为此,您可以使用 ASP.NET MVC 的模型绑定。
并且您应该有一个匹配的 POCO:
以及一个需要您的模型进行绑定的操作:
这应该会自动将您的请求反序列化为 POCO。
Absolutely. You can use ASP.NET MVC's model binding for this.
And you should have a matching POCO:
And an Action which takes your model to bind:
This should automatically deserialize your request into a POCO.