简体   繁体   中英

JSON passing as a null to a method argument

I finally tried to try my hand at using KnockoutJS. I explored for shorter ways to send JSON data to a C# method in MVC 4, but ended up using the AJAX method instead. I have some confusion around the following and was hoping someone could help.

Javascript

var VM = function () {
    var self = this;
    self.ValidateAndCreate = function () {
        console.log("entered");
        var a = {
            b: "1",
            c: "2",
            d: {
                e: "3"
            }
        };
        var input = { data: a }
        console.log(JSON.stringify(input));
        $.ajax({
            url: '/McAfee/ValidateAndCreatePartner',
            data: JSON.stringify(input),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (result) {
                console.log('success');
            }
        });
    }
}
var viewModel = new VM();
ko.applyBindings(viewModel);

C#

    [HttpPost]
    public void ValidateAndCreatePartner(string data)
    {
        var x = JsonConvert.DeserializeObject(data);
        RedirectIfSuccess();
    }

What currently happens is that the ValidateAndCreatePartner fires, but the argument data is null, followed by NewtonSoft.Json.JsonConvert.DeserializeObject failing as a result. How can I resolve this issue?

Since your content type is application/json , the argument to the view function will be automatically deserialized (it's not a string anymore).

Create a viewmodel on the server side matching the one you send and use it as the type argument of the view:

public class D {
    public string e {get;set;}
}

public class A {
    public string b {get;set;}
    public string c {get;set;}
    public D d {get;set;}
}   


[HttpPost]
public void ValidateAndCreatePartner(A data)
{
    // no need to deserialize data
    RedirectIfSuccess();
}

The easiest way in MVC is to create class as per your data : it is much cleaner! For example, with your example, you can try this :

[HttpPost]
public ActionResult Test(TestClass data) {
    RedirectIfSuccess();
}


public class TestClass
{
    public string b { get; set; }
    public string c { get; set; }
    public TestSubClass d { get; set; }
}

public class TestSubClass
{
    public int e { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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