How to get id value from checkboxes checked true to update it on razor?

Ahmed Abd El Aziz 315 Reputation points
2023-06-20T12:34:42.8633333+00:00

I work on asp.net razor .I face issue i can't get group of id selected checkbox true

to update it on razor so can you tell me how to get id values that have checked box true

I need when click button reprintdatabtn then check rows have checkbox checked true then extract id from these rows and pass it to razor to update it

what i try


using jQuery i do as below :

$('#reprintdatabtn').click(function () {
               var dataArr = [];
               $('input:checked').each(function () {

                   dataArr.push($(this).attr('id')); // insert rowid's to array
               });
               console.log(dataArr);

on razor page model

public async task onpost()
{
How to get id 16810,16811 to update it 
}

reprintsdata image

Expected result as image posted must get id

16810 and 16811

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2023-06-20T15:09:32.09+00:00

    You don’t show how you declared the checkboxes. But the browser only posts checkboxes that have a name and are checked. The browser posts the the name and the value. The id is not included.

    if you use the razor tag helper, it renders the value as true, and also a hidden value with their same name whose value is false. The name is the binding name. The postback will be name=false or name=true&name=false

    if posting an array of checkboxes the name should include the array index:

    <input type=“checkbox” name=“test[0]” value=“2345”>


  2. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2023-06-20T19:07:26.4966667+00:00

    your checkboxes will not be included in the post data because they do not have a name attribute. most like you want something like:

    <td><input name="chkList" class="myCheckbox" type="checkbox" value="@reprintid"></t>
    

    and the postback (wrap table with form):

    [BindProperty]
    public string[] chkList {get; set;}
    public async task OnPost()
    {
    
    }
    

  3. Anonymous
    2023-06-22T03:04:45.56+00:00

    Hi @Ahmed Abd El Aziz

    From your code and description, I think you want to send the selected value to the OnPost method using JQuery Ajax method, right? If that is the case, refer to the following sample:

    Program.cs file: register the Antiforgery:

    builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
    

    Reprintslist.cs

        public class Reprintslist
        {
            public int id { get; set; }
            public DateTime LoggedDate { get; set; }
            public string OrderType { get; set; }
            public int OrderNo { get; set; }
            public string PrinterName { get; set; }
            public string BranchCode { get; set; }
            public string Status { get; set; }
        }
    

    ReprintsIndex.cshtml.cs page:

        public class ReprintsIndexModel : PageModel
        {
            [BindProperty]
            public List<Reprintslist> Reprintslist { get; set; }
            public void OnGet()
            {
                Reprintslist = GetReprintslists();
            }
            public List<Reprintslist> GetReprintslists()
            {
                return new List<Reprintslist>()
                {
                    new Reprintslist {id= 16810, LoggedDate = DateTime.Now, OrderType="RB", OrderNo=106808, BranchCode="Jumeira", Status="Printed", PrinterName="printer A"},
                     new Reprintslist {id= 16811, LoggedDate = DateTime.Now, OrderType="RB", OrderNo=106808, BranchCode="Jumeira", Status="Printed", PrinterName="printer A"},
                      new Reprintslist {id= 16812, LoggedDate = DateTime.Now, OrderType="RB", OrderNo=106808, BranchCode="Jumeira", Status="Printed", PrinterName="printer A"},
                       new Reprintslist {id= 16813, LoggedDate = DateTime.Now, OrderType="RB", OrderNo=106808, BranchCode="Jumeira", Status="Printed", PrinterName="printer A"},
                        new Reprintslist {id= 16814, LoggedDate = DateTime.Now, OrderType="RB", OrderNo=106808, BranchCode="Jumeira", Status="Printed", PrinterName="printer A"},
                };
            }
            public IActionResult OnPost(string[] selectedids)
            {
                
    
    
                return new JsonResult("success");
            }
             
        }
    

    ReprintsIndex.cshtml page:

    @page "/reprientsindex"
    @model RazorWebApp.Pages.ReprintsIndexModel
    
    @Html.AntiForgeryToken()
    <button id="reprintdatabtn" style="margin-Left:10px;width:100px;" class="btn btn-primary">Reprint</button>
    
    <table id="example" class="display">
        <thead>
            <tr>
    
                <th><input id="chkHeader" type="checkbox"></th>
                <th>EntredDatetime</th>
                <th>OrderType</th>
                <th>OrderNo</th>
                <th>PrinterName</th>
                <th>BranchCode</th>
                <th>Status</th>
                <th>Id</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var reprint in Model.Reprintslist)
            {
                <tr>
    
                    <td><input id="chkSel" class="myCheckbox" type="checkbox"></td>
                    <td>@reprint.LoggedDate</td>
                    <td>@reprint.OrderType</td>
                    <td>@reprint.OrderNo</td>
                    <td>@reprint.PrinterName</td>
                    <td>@reprint.BranchCode</td>
                    <td>@reprint.Status</td>
                    <td id="idval">@reprint.id</td>
    
                </tr>
            }
        </tbody>
    </table>
    
    @section Scripts{
        <script>
            $(function(){
                $('#reprintdatabtn').click(function () {
                    var dataArr = [];
                    $('input:checked').each(function () {
    
                        dataArr.push($(this).closest("tr").find("#idval").html()); // insert rowid's to array
                    });
                    console.log(dataArr);
    
                    $.ajax({
                        type: "POST",
                        url: "/reprientsindex",
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
                        data:{selectedids: dataArr}, 
                        success: function (response) {
                            alert(response);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        },
                        error: function (response) {
                            alert(response.responseText);
                        }
                    });
                });
            });
        </script>
    }
    

    The result as below:

    image2


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    0 comments No comments

  4. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-06-22T16:57:34.9566667+00:00

    Unsure why scripting is needed, this can be done with C#. Here is an example where for this ignore the property Category.

    public partial class Note
    {
        public int NoteId { get; set; }
    
        [Display(Name = "Note")]
        [Required]
        [MinLength(6)]
        public string BodyText { get; set; }
    
        [GreaterThan("11/1/2022")]
        [Display(Name = "Due by")]
        [DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:dd/MM/yyyy HH:mm tt}")]
        public DateTime? DueDate { get; set; }
    
        [Required]
        [Display(Name = "Done")]
        public bool Completed { get; set; }
        public int? CategoryId { get; set; }
    
        public virtual Category Category { get; set; }
    }
    

    Frontend

    @page
    @model NotesRazorApp.Pages.ViewAllNotesModel
    
    @{
        ViewData["Title"] = "ViewAllNotes";
    }
    
    <h1>Get checked</h1>
    
    
    <form method="post">
        <table class="table">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Notes[0].BodyText)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Notes[0].DueDate)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Notes[0].Completed)
                    </th>
    
                </tr>
            </thead>
            <tbody>
    
                @for (int index = 0; index < Model.Notes.Count; index++)
                {
                    <tr>
                        <input type="hidden" asp-for="Notes[index].NoteId" />
                        <td>
                            <input type="hidden" asp-for="Notes[index].BodyText"/>
                            @Model.Notes[index].BodyText
                        </td>
                        <td>
                            <input type="hidden" asp-for="Notes[index].DueDate"/>
                            @Model.Notes[index].DueDate
                        </td>
                        <td>
                            <input asp-for="Notes[index].Completed" />
                        </td>
                    </tr>
                }
    
            </tbody>
        </table>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    

    Backend (uses SeriLog)

    public class ViewAllNotesModel : PageModel
    {
        private readonly Data.Context _context;
    
        public ViewAllNotesModel(Data.Context context)
        {
            _context = context;
        }
    
        [BindProperty]
        public IList<Note> Notes { get;set; } = default!;
    
        public async Task OnGetAsync()
        {
            if (_context.Note != null)
            {
                Notes = await _context
                    .Note
                    .Include(note => note.Category)
                    .ToListAsync();
            }
        }
    
        public void OnPost()
        {
            // get identifiers for checked notes
            var checkedNotes = Notes
                .Where(note => note.Completed)
                .Select(x => x.NoteId)
                .ToArray();
    
            if (checkedNotes.Any())
            {
                // do something with the identifiers
                Log.Information(string.Join(",", checkedNotes));
            }
            else
            {
                Log.Information("Nothing checked");
            }
        }
    }
    

    Screenshot getChecked

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.