2

Ok, so my question is two pronged. I am trying to retrieve specific string values from selected rows into a JQuery array:

<script>
var finalCSG=[]; 
$('.checkbox').change(function () {
        var csg = [];
        var checkedRows = $('.checkbox:checked'); 
        $.each(checkedRows, function (index, item) 
        { 
            var row = $(this).closest('tr');
            csg.push(row.find('.connote').text());
        })
        finalCsg = csg;
    });
</script>

My first question: The contents of array 'finalCsg' are supposed to be simple alphanumeric strings, but they contain lots of leading and trailing spaces (when I used console.log to check them out). How do I resolve this?

Now, the second and more pressing issue. I try to pass this array to my MVC controller (with a button click), with the following code:

var url = '@Url.Action("Assign", "TransactionHistory")';
    document.getElementById("AssignButton").onclick = function () { myFunction() };
    function myFunction() {

        $('#myDiv').load(url, { csgList: finalCsg })
    }

'TransactionHistory' is my controller name. Even here, the variable csgList contains the proper array elements (with those spaces I described earlier, though, when I check with console.log). But my controller only gets a null string. The controller is defined like this:

    [HttpPost]
    public ActionResult Assign(List<string> csgList)
    { 
        return Content("Hi");
    }

I initially tried using string[] csgList as the parameter, and then tried List but it always gets a null value (or empty string I guess) from JQuery (The return statement is just to test, does not really mean much now). Some posts mention the use of a 'traditional' keyword, but I am not primarily a front end developer (I am covering for someone at work, with strict deadlines) so I couldn't use that to proper effect.

Any inputs would be greatly beneficial.

4
  • Your parameter is an collection, so the data needs to be { [0].csgList: someValue, [1].csgList: anotherValue, .... } (i,e. indexed) or you need to stringify the data and set contentType: 'json' (or you can use traditional: true option. Its easier to do this using $.ajax(). Commented Jan 25, 2017 at 10:37
  • Either string[] or IEnumerable<string> or List<string>` are all fine. But you cannot pass csgList as it is. It needs to be as I noted in the first comment - e.g. stringified using JSON.stringify() and set the contentType option Commented Jan 25, 2017 at 11:16
  • But if I need to change JQuery code, where exactly do I make the changes you specified (like stringifying the data, using$.ajax(), setting traditional: true etc.)? Commented Jan 25, 2017 at 11:19
  • Ok, thanks a ton! I'll be waiting for that. The answer could save my job...for now, untl I seek a different one which matches my skillset. Commented Jan 25, 2017 at 11:27

1 Answer 1

3

Since you passing an array of simple values, then you can use the traditional: true ajax option to correctly bind to your List<string> csgList.

var url = '@Url.Action("Assign", "TransactionHistory")';
var element = $('#myDiv');
$.ajax({
    url: url,
    type: 'POST',
    traditional: true,
    data: { csgList: finalCsg },
    success: function (response) {
        element.html(response);
    }
});

An alternative is to stringify the data and set the contentType option (and this alternative is required if your array contains objects rather than simple values)

$.ajax({
    url: url,
    type: 'POST',
    data: JSON.stringify({ csgList: finalCsg }),
    contentType: "application/json; charset=utf-8",
    success: function (response) {
        element.html(response);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! Could you please let me know how your code can be triggered when I click the button with the id 'AssignButton'? Do I need to put your code after document.getElementById("AssignButton").onclick = or can I replace it with $('#AssignmentButton').Click()?
$('#AssignButton').click(function(){ ...ajax call ... })

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.