简体   繁体   中英

Asp.net core mvc send array of int to controller

So I do Ajax and then I have this piece of code (JavaScript):

document.getElementById("HidenLink").style.visibility = "visible";
document.getElementById("HidenLink").innerHTML = "I have found " + data.pocetfound + " cases";
var arrStr = encodeURIComponent(JSON.stringify(data.listfound));
var Path = " ";
switch ('@ViewBag.TableName') {
         case "MYCASE":
              Path = "PATJ/PATHH"
         break;
       }
document.getElementById("HidenLink").href = Path + '/IDArr?array=' + arrStr;

Then I expect to get int[] IDArr in my Controller:

[HttpGet]
public async Task<IActionResult> MYRIGHTPATH(int? id, int[] IDArr)
{
  try {
    /*TESTS*/
     foreach (int i in IDArr) //Does not get executed
      {
         Console.WriteLine(i);
      }
        /*TESTS*/
   }catch (Exception e) {
                return RedirectToAction("Error", new { error = e });
            }
        }

My endpoint:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

My problem is that controller does not get array I am trying to send.

Thanks for help!

expect to get int[] IDArr in my Controller

[HttpGet]
public async Task<IActionResult> MYRIGHTPATH(int? id, int[] IDArr)`

To achieve your requirement, you can pass the data through query string like below.

?IDArr=1&IDArr=2

Or

?IDArr[0]=1&IDArr[1]=2

Test Result

在此处输入图像描述

For more information about model binding, please check this doc: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1#collections

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