2

I have a controller that takes a List<int> and I am calling from AJAX. The controller is hit, but the parameter is always null.

My controller:

public ActionResult MinorAreas(List<int> majorareas)
{
    // ...
}

jQuery call:

function onChange(e)
{
   var cur = this.value(); // an array of numbers like [2,4,7,9]

   $.ajax({
       cache: false,
       type: "GET",
       traditional: true,
       url: "@(Url.RouteUrl("GetMinorAreas"))",
       data: { "majorareas": cur},
       success: function (data) {...},
       error: function (xhr, ajaxOptions, thrownError) {... }
   });

 }

Route definition:

routes.MapLocalizedRoute(
    "GetMinorAreas",
    "minorAreas",
    new { controller="ProSearch", action="MinorAreas", majorareas=new List<int>() },
    new[] { "ABC.ZZZ.Controllers" }
);

Using fiddler, I can see that the URI is built correctly:

# With an array of [2]
http://localhost:15536/minorAreas?majorareas=2&_=1450307693166

# With an array of [2,3,9]
http://localhost:15536/minorAreas?majorareas=2&majorareas=3&majorareas=9&_=1450308261808

I've already looked at this question about passing arrays to a controller with a List<int> parameter, but the solution doesn't seem to work for me. What am I doing wrong?

7
  • Can you edit and provide the actual network request? Your JSON may not be formatted properly. Commented Dec 16, 2015 at 21:43
  • Ohhh duh...I should have thought of that. Yes coming right up. Commented Dec 16, 2015 at 21:44
  • Added fiddler capture Commented Dec 16, 2015 at 23:26
  • It does look like the values are being passed (as separate querystring arguments), which should work. Does this have to be a GET? You might have more luck with a POST. Commented Dec 16, 2015 at 23:29
  • Why are you doing majorareas=new List<int>() in the route definition? Commented Dec 16, 2015 at 23:31

1 Answer 1

1

It looks like the network request is being generated correctly. The problem is in the route definition:

routes.MapLocalizedRoute(
    "GetMinorAreas",
    "minorAreas",
    new { controller="ProSearch", action="MinorAreas", majorareas=new List<int>() },
    new[] { "ABC.ZZZ.Controllers" }
);

majorareas=new List<int>() is going to ensure that majorareas is always an empty list, even when it otherwise would be populated!

You don't have to define parameters here; the method definition in the controller does that. Leave it off, and it should work fine:

routes.MapLocalizedRoute(
    "GetMinorAreas",
    "minorAreas",
    new { controller="ProSearch", action="MinorAreas" },
    new[] { "ABC.ZZZ.Controllers" }
);
Sign up to request clarification or add additional context in comments.

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.