1

I'm having some problem with passing a javascript array to the controller. I have several checkboxes on my View, when a checkbox is checked, its ID will be saved to an array and then I need to use that array in the controller. Here are the code:

VIEW:

<script type="text/javascript">
        var selectedSearchUsers = new Array();
        $(document).ready(function () {
            $("#userSearch").click(function () {
                selectedSearchUsers.length = 0;
                ShowLoading();
                $.ajax({
                    type: "POST",
                    url: '/manage/searchusers',
                    dataType: "json",
                    data: $("#userSearchForm").serialize(),
                    success: function (result) { UserSearchSuccess(result); },
                    cache: false,
                    complete: function () { HideLoading(); }
                });
            });
            $(".userSearchOption").live("change", function () {
                var box = $(this);
                var id = box.attr("dataId");

                var checked = box.attr("checked");

                if (checked) {
                    selectedSearchUsers.push(id);
                }
                else {
                    selectedSearchUsers.splice(selectedSearchUsers.indexOf(id), 1);
                }
            });
            $("#Send").click(function () {
                var postUserIDs = { values: selectedSearchUsers };
                ShowLoading();
                $.post("/Manage/ComposeMessage",
                postUserIDs,
               function (data) { }, "json");
            });
    });
</script>

When the "Send" button is clicked, I want to pass the selectedSearchUsers to the "ComposeMessage" action. Here is the Action code:

public JsonResult ComposeMessage(List<String> values)
        {
            //int count = selectedSearchUsers.Length;
            string count = values.Count.ToString();
            return Json(count);
        }

However, the List values is always null. Any idea why?

Thank you very much.

Harry
  • 87,580
  • 25
  • 202
  • 214
Xuan Vu
  • 247
  • 1
  • 4
  • 15
  • Sounds similar to this question http://stackoverflow.com/questions/2527658/jquery-sortable-toarray-with-asp-net-mvc-actionresult – Roman Apr 22 '10 at 01:22
  • I've tried that solution but still getting null when passing they array into my controller. Anyone? Thanks. – Xuan Vu Apr 22 '10 at 03:07

1 Answers1

2

You might try changing the controller's action method to this:

[HttpPost]
public JsonResult ComposeMessage(string values) 
{
    JavaScriptSerializer jass = new JavaScriptSerializer; 
    AnyClass myobj = jass.Deserialize<AnyClass>((string)values);
    ...
    ... 
}

I believe that you have to take the JSON data in as a string and do the conversion manually. Hope it helps. Cheers.