0

Using ajax I want to pass 2 objects: string[] and Options to my controller. The problem is that every time string[] in controller scope is set to null.

Thats js code:

$("#exportCsv").click(function () {
    var checkboxes = $('.TableChBox:checkbox:checked');
    var allIds = [];
    for (var i = 0, n = checkboxes.length; i < n; ++i) {
        var el = checkboxes[i];
        if (el.id) {
            allIds.push(el.id);
        }
    }
    console.log(allIds); // it prints ["RId1604678", "RId1604679"]
    
    var form = $('#SearchForm').serialize();

    $.ajax({
        url: '@Url.Action("ExportToCsv", "Bank")',
        type: 'POST',
        data: JSON.stringify({
            ids: allIds,
            options: form
        }),

        dataType: 'json',
        error: function (xhr) {
            alert('Error: ' + xhr.statusText);
        },
        async: true,
    });
});

And thats c# code:

public void ExportToCsv(string[] ids, Options options)
{
    // ids is null here
    // options is not null
}

When I use debugger I can see, that options is successfully filled, but ids is null. Why does that happen?

Edit 1

As someone suggested I should Add contentType. So I added:

url: '@Url.Action("ExportToCsv", "Bank")',
type: 'POST',
contentType: "application/json; charset=utf-8",

And still - ids is not null, but options is.

Edit 2

Someone suggested to change two parameters in function to one. So I changed my code to:

part of controller

public class ExportModel
{
    [JsonProperty(PropertyName = "one")]
    public string One { get; set; }

    [JsonProperty(PropertyName = "two")]
    public string Two { get; set; }
}

[System.Web.Mvc.HttpPost]
public void ExportToCsv([System.Web.Http.FromBody] ExportModel model)
{
    //model.One is null
    //model.Two is null
}

part of js code

data: JSON.stringify({
    one: "foo",
    two: "bar"
}),

And even with that simple example with two strings it is not working.

3
  • Sorry, you don't need [FromBody] for MVC. I thought you were using WebApi. I thought you'd undone the changes from that. Remove the namespace you had to reference, set your attributes back to how they were, and try my answer as it stands now. Commented Jun 12, 2018 at 12:41
  • @john it still doesnt work. Whats more interesting, when I add contentType: "application/json" now Options is not being parsed properly. Commented Jun 12, 2018 at 13:03
  • Well, this code is working flawlessly for me, so I'm at a loss as to what your problem is now. Note that I'm putting a breakpoint on line 15 and inspecting the value of t. Commented Jun 12, 2018 at 13:07

2 Answers 2

1

In your controller method you should declare it as accepting a model like so:

public void ExportToCsv(ExportModel model)
{

}

And then define your model like so:

public class ExportModel
{
    [JsonProperty(PropertyName = "ids")]
    public string[] Ids {get;set;}

    [JsonProperty(PropertyName = "options")]
    public Options Options {get;set;}
}

As patilprashant6792 pointed out, your ajax request is missing the content type, so you should replace it with this:

$("#exportCsv").click(function () {
    var checkboxes = $('.TableChBox:checkbox:checked');
    var allIds = [];
    for (var i = 0, n = checkboxes.length; i < n; ++i) {
        var el = checkboxes[i];
        if (el.id) {
            allIds.push(el.id);
        }
    }
    console.log(allIds); // it prints ["RId1604678", "RId1604679"]

    var form = $('#SearchForm').serialize();

    $.ajax({
        url: '@Url.Action("ExportToCsv", "Bank")',
        type: 'POST',
        data: JSON.stringify({
            ids: allIds,
            options: form
        }),
        contentType: 'application/json',
        dataType: 'json',
        error: function (xhr) {
            alert('Error: ' + xhr.statusText);
        },
        async: true,
    });
});

If you don't declare the content type, it will default to application/x-www-form-urlencoded; charset=UTF-8

Sign up to request clarification or add additional context in comments.

5 Comments

What is FromBody attribude? I cant use it. It says The type or namespace name 'FromBody' could not be found (are you missing a using directive or an assembly reference?). When I delete that attribute now ids and options are both null.
Still both are null. I addeed System.Web.Http and now code started to compile. Bad thing is that I had to change every [HttpPost] attribute to [System.Web.Mvc.HttpPost] because System.Web.Http is in conflict with System.Web.Mvc.
Please add contentType as 'application/json' in you ajax function and the above code works even without the from body tag
@patilprashant6792 Unfortunelly your suggestions are not working for me. I edited my code.
@john thats asp.net mvc5 project, not web api.
0

You should use list of string instead of array & try.

public List<string> Ids {get;set;}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.