• 0

Passing array of int to mvc controller with javascript


 Share

Question

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 :)

Link to comment
Share on other sites

6 answers to this question

Recommended Posts

  • 0
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. 

Link to comment
Share on other sites

  • 0

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 },
	...
});

 

Link to comment
Share on other sites

  • 0
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
Link to comment
Share on other sites

  • 0
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
Link to comment
Share on other sites

  • 0
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). 

Link to comment
Share on other sites

This topic is now closed to further replies.
 Share

  • Recently Browsing   0 members

    No registered users viewing this page.