vendredi 20 novembre 2020

Check all the checkboxes with jQuery and JSon asp.net mvc

I have three checkbox

<input name="Selected" value="1" type="checkbox" />
<input name="Selected" value="2" type="checkbox" />
<input name="Selected" value="3" type="checkbox" />

and a method that returns some numbers of database that equals to checkbox value

public ActionResult GetSelectedPGs(int id)
{
     var data = db.AccountRepository.GetSelectedPGsByProductId(id)
          .Select(g => new {Value = g.GroupId}); 
     return Json(data, JsonRequestBehavior.AllowGet);
}

The Above method returns the stored checkbox values in my database

I want a Script that When the page is loading, if my method for example returns 1 and 2 the checkbox with value = 1 and value = 2 to be checked... I wrote a script with my none knowledge of JavaScript

  $(document).ready(function() {
           $.getJSON("/Home/GetSelectedPGs/" + @Model.ProductId),
               function(result) {
                   $("input[name='Selected']").each( function (index) {
                       $.each(result,
                           function(Index, item) {
                               if (item.Value === index.val()) {
                                   index.prop('checked', true);
                               }
                           }
                       );
                   });

               }
       });

And obviously its not working! I appriciate any help.




Aucun commentaire:

Enregistrer un commentaire