0

I have a dynamic list and I need to return the selected items from view back to the controller. I have checked the link CheckboxList in MVC3 View and get the checked items passed to the controller the problem is i have a dynamic list and i need to display it horizontally so i am using

<table>
  <tr>
  @foreach (var item in mylist)
  {
  <td><img src='@item.PictureUrl'/><br />@Html.CheckBox(@item.Id,@item.checkedin)@item.Name</td>
 }
 </tr>
</table>

I also have a textarea in the same form.

In the controller post method, I am able to access the textarea value but not the list or checked items. please help.

Or is there any other better way to display my list and get back the checklist items?

I am new to MVC, any help would be appreciated.

Thanks

Community
  • 1
  • 1

1 Answers1

0

Using the JQuery is the best way: 1- Download Jquery.json.js and add it to your view:

 <script src="../../Scripts/jquery.json.js" type="text/javascript"></script>

2- add a ".cssMyClass" to all checkboxes so you can grab the values by their css class:

 <script type="text/javascript" >
       $(document).ready(function () {
           $("#btnSubmit").click(sendValues);
         });

     function populateValues()
     {
         var data = new Array();
         $('.myCssClas').each(function () {
             if ($(this).attr('checked')) {
                 var x = $(this).attr("value");
                 data.push(x);
             }
         }); 

         return data;
     }

     function sendValues() {
         var data = populateValues();
               $.ajax({
                   type: 'POST',
                   url: '@Url.Content("~/Home/Save")',
                   data: $.json.encode(data),
                   dataType: 'json',
                   contentType: 'application/json; charset=utf-8',
                   success: function () { alert("1"); }
               });

       } 



 </script>

As you can see I've added all selected values to an Array and I've passed it to "Save" action of "Home" controller by ajax
*- in Controller you can receive the values by adding an array as argument:

 [HttpPost]
        public ActionResult Save(int[] val)
        {

I've searched too much but apparently this is the only solution. Please let me know if you find a better solution for it.

Amir978
  • 857
  • 3
  • 15
  • 38