I have a modal dialog in MVC3 where im passing a parameter to the controller like this:
$("#SelectedCSIDivisionCodes").live("click", function () {
var ID = $(this).val();
$.ajax({
type: "GET",
url: '@Url.Action("GetCSICodes", "CSICodes")',
data: { divisionID: ID },
dataType: "json",
error: function (xhr, status, error) {
alert(xhr);
alert(status);
alert(error);
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
alert("Data Returned: " + json);
}
});
// $.getJSON(, { divisionID: ID }, function (data) {
// alert(data);
// });
});
And I’m receiving the parameter like this:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCSICodes(string divisionID)
{
int ID = Convert.ToInt32(divisionID);
var csiCodes = (from c in EFProject.CSICode
where c.DivisionID == ID
select c).OrderBy(x => x.CSICodeID);
List<SelectListItem> codes = new List<SelectListItem>();
foreach (var code in csiCodes)
{
codes.Add(new SelectListItem { Value = code.CSICodeID.ToString(), Text = code.Code + " " + code.Name });
}
return Json(codes.AsEnumerable(), JsonRequestBehavior.AllowGet);
}
The ajax call works fine but its not detecting the parameter value in the controller. In other words, I’m getting null in the variable divisionID only in the controller. I used firefox to see if im setting a value and it seems that it is doing it because it returns this URL:
GET http://localhost:1925/CSICodes/GetCSICodes?divisionID%5B%5D=2 [HTTP/1.1 200 OK 95690ms]
Any ideas of what could be wrong?
Your Action is expecting a parameter of type string, but its getting a parameter of an array type.
Url should end divisionID=2, instead it’s ending divisionID[]=2 (an array with 1 value of 2).
In certain circumstances, it’s possible for the val() function to return an array. See http://api.jquery.com/val/ for details.