I have an array in JQuery which holds the Id & value of attributes I need to pass to the MVC controller. The array seems to populate correctly in Jquery and the ajax post to the controller works too. However, the value being passed back to the controller appears as a flat single element in the controller array (i.e. all array values are flattened into 1 sequential string value).
Here is the jquery:
var attListArray = new Array();
table.find('tr').each(function (i, el) {
var tds = $(this).find('td'),
attName = tds.eq(0).text(),
attValue = tds.eq(1).text(),
attId = tds.eq(2).text();
attListArray[i] = attId + '~' + attValue;
alert(attListArray[i] + ' - ' + i);
});
$.ajax({
type: "POST",
async: true,
contentType: "application/json;charset=utf-8",
url: "@Url.Action("SaveForm", "Home")",
data: '{"parms":"' + formElements + '" , "attList":"' + attListArray + '"}' ,
dataType: "json",
traditional: true,
success: function (data) {
alert("success");
},
error: function () {
alert("An error has occurred");
}
});
The controller action is:
public JsonResult SaveForm(string parms, List<string> attList)
{
Models.Result result = new Models.Result(false, "None");
NameValueCollection qscoll = HttpUtility.ParseQueryString(parms);
string s1 = "";
string s2 = "";
foreach (String s in qscoll.AllKeys)
{
s1 = s1 + " , " + s;
s2 = s2 + " , " + qscoll[s];
//Console.WriteLine(" {0,-10} {1}", s, qscoll[s]);
}
try
{
result.Success = true;
}
catch (Exception ex)
{
result.Success = false;
result.Error = ex.Message;
//log to event log
//DRS_Repository.LogEvent(ex.Message, ex.Source);
}
return Json(result, JsonRequestBehavior.AllowGet);
}
As an example, I have 2 strings in 2 array cells: [0] = '56~z', [1] = '59~x'. But When the array is passed to the controller, the List attList contains 1 count of a string = '56~z,59~x'. I was expecting the array to have a count of 2 & the elements to be passed into the list or array as separate elements:
e.g. attList[0]="56~z" and attList[1]="59~x"
But I can't get this result. I've tried passing to string[] attList, I've tried adding square & curly brackets around the array in the jquery and I've tried to JSON.Stringify the array but I can't get the array to pass as a list/array to the controller.
Could someone explain where I'm going wrong?
Thanks in advance.
Shuja