简体   繁体   English

如何将AJAX / Jquery对象发送到Controller(差异)MVC4

[英]How to send AJAX/Jquery object to Controller (discrepancy) MVC4

I have had this confusion for a while and it's because of the following reason: 我有一段时间的困惑是因为以下原因:

I am trying to send a jquery object 我正在尝试发送一个jQuery对象

var myObject = {
                    Title: $('#Title').val(),
                    Title2: $('#Title2').val(),
                    Title3: $('#Title3').val(),
                };

through an ajax call 通过ajax调用

                    $.ajax({
                    data: { myObjectName = myObject
                    },
                    datatype: "json",
                    url: "myUrl",
                    cache: false,
                    error: function (ts)
                    {//handle error},
                    success: function (result)
                    {//handle success}
                });

I'm receiving my object in my controller like this: 我在控制器中收到这样的对象:

public ActionResult MyAction(ObjectType myObjectName)

However, when receiving the object from javascript, it does not recognize it as such and just instantiates a new ObjectType. 但是,当从javascript接收对象时,它不能这样识别对象,而只是实例化一个新的ObjectType。

I know I can send it as a string, serialize it if I put my object inside a form, etc...what I want to know is why this approach seems to work for me sometimes (I have gotten it to work with other ObjectType(s)) and in other instances it doesn't. 我知道我可以将其作为字符串发送,如果将对象放入表单中则可以序列化,等等...我想知道的是为什么这种方法有时似乎对我有用(我已经将它与其他ObjectType一起使用(s)),在其他情况下则没有。 Does it have anything to do with how complex the object is? 它与对象的复杂程度有关系吗? Sending an incomplete object? 发送不完整的对象? (The latter one doesn't seem to be it since I have sent 'incomplete' objects and the empty fields just get instantiated with null) (后一个似乎不是,因为我发送了“不完整”的对象,而空字段只是用null实例化了)

ANY insight would be appreciated. 任何见识将不胜感激。 Thanks! 谢谢!

Change your code to; 将您的代码更改为;

$.ajax({
    data: myObject,
    datatype: "application/json",
    type: "POST",
    url: "myUrl",
    cache: false,
    error: function (ts)
    {//handle error},
    success: function (result)
    {//handle success}
});

Notice that the type is a POST which means you will also need to add [HttpPost] to your ActioResult. 请注意,该类型是POST,这意味着您还需要将[HttpPost]添加到ActioResult。

As long as ObjectType is a class with the fields 只要ObjectType是具有字段的类

public class ObjectType
{
    public string Title { get; set; }
    public string Title2 { get; set; }
    public string Title3 { get; set; }
}

Your current code is attempting to bind your model to something which would resemble 您当前的代码正在尝试将您的模型绑定到类似于

public class SomeObject
{
    ObjectType myObjectName { get; set; }
}

public class ObjectType{
    public string Title { get; set; }
    public string Title2 { get; set; }
    public string Title3 { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM