• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

  • 0
Sign in to follow this  

Passing array of int to mvc controller with javascript

Question

Martin.D    0

Hi,

 

Im having an issue i passing the selected items from a grid to method on a controller.

 

My View looks like this;

 

<script type="text/javascript" language="javascript">

    function ClearInterfaceState() {
        var items = {};
        var grid = $('#Visits').data('kendoGrid');
        var selectedElements = grid.select();

        for (var j = 0; j < selectedElements.length; j++) {
            var item = grid.dataItem(selectedElements[j]);
            items[j] = item.VisitId;
        }

        var MyAppUrlSettings = {
            MyUsefulUrl : '@Url.Action("ClearInterfaceState","QuickFixes")'
        }
        
        $.ajax({
            url: MyAppUrlSettings.MyUsefulUrl,
            data: items,
            type: "post",
            dataType: "json",
            contextType: "application/json",
            traditional: true,
            success: function (result) {
                alert("Successfully changed");
            },
            error: function (_err) {
                alert(_err);
            }
        });

    };
</script>

 

The data in the items variable is there as I put an alert in to double check. The issue seems to be with the controller as the items is null?

 

        [Authorize]
        [HttpPost]
        public JsonResult ClearInterfaceState(int[] items)
        {
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
            // Some Code
        }

 

 

Any help with this would be great as I've only been developing for a year now and javascript is still a mystery to me :)

Share this post


Link to post
Share on other sites

6 answers to this question

Recommended Posts

  • 0
adrynalyne    13,024
1 hour ago, Martin.D said:

Hi,

 

Im having an issue i passing the selected items from a grid to method on a controller.

 

My View looks like this;

 

<script type="text/javascript" language="javascript">

    function ClearInterfaceState() {
        var items = {};
        var grid = $('#Visits').data('kendoGrid');
        var selectedElements = grid.select();

        for (var j = 0; j < selectedElements.length; j++) {
            var item = grid.dataItem(selectedElements[j]);
            items[j] = item.VisitId;
        }

        var MyAppUrlSettings = {
            MyUsefulUrl : '@Url.Action("ClearInterfaceState","QuickFixes")'
        }
        
        $.ajax({
            url: MyAppUrlSettings.MyUsefulUrl,
            data: items,
            type: "post",
            dataType: "json",
            contextType: "application/json",
            traditional: true,
            success: function (result) {
                alert("Successfully changed");
            },
            error: function (_err) {
                alert(_err);
            }
        });

    };
</script>

 

The data in the items variable is there as I put an alert in to double check. The issue seems to be with the controller as the items is null?

 

        [Authorize]
        [HttpPost]
        public JsonResult ClearInterfaceState(int[] items)
        {
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
            // Some Code
        }

 

 

Any help with this would be great as I've only been developing for a year now and javascript is still a mystery to me :)

A couple things. 
1.  Kendo is garbage. 
2. You need to convert your data to a json string. Use JSON.stringify. 

Share this post


Link to post
Share on other sites
  • 0
ZakO    521

You don't need to stringify it yourself, jQuery $.ajax handles that for you.

 

The problem is you're sending an array but the ASP.NET model binder is expecting an object (well, string representation of one) to know which parameter to bind to even though you only have one. Change it to:

$.ajax({
	...
	data: { items: items },
	...
});

 

Share this post


Link to post
Share on other sites
  • 0
adrynalyne    13,024
On 2/19/2020 at 12:03 PM, ZakO said:

You don't need to stringify it yourself, jQuery $.ajax handles that for you.

 

The problem is you're sending an array but the ASP.NET model binder is expecting an object (well, string representation of one) to know which parameter to bind to even though you only have one. Change it to:


$.ajax({
	...
	data: { items: items },
	...
});

 

Forgive me if I do not agree.

 

Here is a working example solution that I threw together real quick. It requires .net core 3.1.

Things of note:

  • I simply return the POST data that comes in.
  • Using jquery ajax without stringifying the data does not work.
  • Using jquery ajax with stringifying the data does work.
  • Using your data structure of sending it as a named JSON object also does not work.

https://1drv.ms/u/s!AiOH5gkEn6Zfj8FMW-5PTou4SUEeaQ?e=l1ocdq

 

Edited by adrynalyne
Fixed link

Share this post


Link to post
Share on other sites
  • 0
ZakO    521

editing example

Edited by ZakO

Share this post


Link to post
Share on other sites
  • 0
ZakO    521
6 hours ago, adrynalyne said:

Forgive me if I do not agree.

 

Here is a working example solution that I threw together real quick. It requires .net core 3.1.

Things of note:

  • I simply return the POST data that comes in.
  • Using jquery ajax without stringifying the data does not work.
  • Using jquery ajax with stringifying the data does work.
  • Using your data structure of sending it as a named JSON object also does not work.

https://1drv.ms/u/s!AiOH5gkEn6Zfj8FMW-5PTou4SUEeaQ?e=l1ocdq

 

My bad, you're right, for proper JSON requests it does need that, the OPs example threw me off. There's another bug in the OPs code they have contextType instead of contentType as the option so when I was testing (hadn't used jQuery for a long time) the model binder was checking encoded form fields instead of JSON. 

Edited by ZakO
  • Like 1

Share this post


Link to post
Share on other sites
  • 0
adrynalyne    13,024
4 minutes ago, ZakO said:

My bad, you're right, for proper JSON requests it does need that, the OPs example threw me off. There'a another bug in the OPs code they have contextType instead of contentType as the option so when I was testing (hadn't used jQuery for a long time) the model binder was checking encoded form fields instead of JSON. 

Ah yup. Good catch. Admittedly, I have tried to move away from JQuery as much as possible so I’m a little rusty with it. 

 

I usually end up having to write vanilla JS for space constraints (iot devices). 

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.