• 0

Passing array of int to mvc controller with javascript


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

6 answers to this question

Recommended Posts

  • 0
  On 19/02/2020 at 10:45, 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 :)

Expand  

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

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

 

  • 0
  On 19/02/2020 at 19:03, 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 },
	...
});

 

Expand  

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
  • 0
  On 22/02/2020 at 19:46, 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

 

Expand  

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
  • 0
  On 23/02/2020 at 02:21, 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. 

Expand  

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

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
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • And this is why I always wait at least a week after a Patch Tuesday before updating the servers. No headaches over here.
    • Windows is a scam for many decades, it's good if some people are realizing it now
    • Latest Patch Tuesday has broken DHCP Server in all Windows Server editions by Usama Jawad Microsoft released Patch Tuesday updates for Windows and Windows Server releases roughly a week ago, on June 10. In the latter, the release contained new functions for Narrator scan mode, along with tons of fixes for File Explorer, GDI+, Hyper-V, and more. At that time, Microsoft noted a known issue for Noto fonts, where Chinese, Japanese, and Korean text appears blurry or unclear under certain conditions. Now, it has highlighted another known issue following user reports. For the past couple of days, users on Reddit have been reporting issues with the DHCP service after applying the latest Patch Tuesday update. Apparently, rebooting the system fixes the issue, which can be understandably annoying. Now, Microsoft has updated the documentation for the June 10 release notes across Windows Server 2016, 2019, 2022, and 2025, to mention that the DHCP Server service may "intermittently" stop working after installing Patch Tuesday's update, which will impact IP renewal processes on client machines. Redmond has assured customers that it is working on a fix, which will likely be rolled out within the next few days. Of course, this problem is rather frustrating for IT admins, and that annoyance is reflected in the Reddit thread where customers are blaming Microsoft's software quality assurance practices. The fact that it's currently unclear when a fix will be rolled out may further add to customer grievances. For those unaware, the DHCP Server service in Windows is responsible for network management such as allocation and configuration of IP addresses in a centralized environment with robust logging and monitoring mechanisms. And for those keeping track, this is not the only Windows Server issue that has cropped up in recent memory. Last month, Microsoft pushed an out-of-band (OOB) hotfix to patch a Hyper-V bug that was plaguing the platform. Of course, one can argue that problems like these are happening because of incomplete testing, but it is also important to remember that Windows is running on hundreds of millions of devices all over the globe, so comprehensive test case coverage is very difficult, if not impossible.
    • And still, no Windows Hello support for protected "tabs" in the "old"/Win32 OneNote app, a feature that was available for a long time in the UWP version. Please, Microsoft, get back to feature parity...
    • Like jupe, for me, the most exciting news from Windows for a few weeks ( / months ?) now is the return of the clock in the taskbar calendar. I filed a feedback hub post so long ago about this. Finally!
  • Recent Achievements

    • Week One Done
      patrickft456 earned a badge
      Week One Done
    • One Month Later
      patrickft456 earned a badge
      One Month Later
    • One Month Later
      Jdoe25 earned a badge
      One Month Later
    • Explorer
      Legend20 went up a rank
      Explorer
    • One Month Later
      jezzzy earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      617
    2. 2
      ATLien_0
      281
    3. 3
      +FloatingFatMan
      174
    4. 4
      Michael Scrip
      153
    5. 5
      Steven P.
      124
  • Tell a friend

    Love Neowin? Tell a friend!