Search code examples
jqueryajaxasp.net-mvcasp.net-corerazor-pages

How to fill checkboxes by ajax request to function RelatedUserAccessPermission on razor page mvc?


I work on .NET core 7 MVC razor page . I face issue I can't fill check boxes Id StockTake and ShelfLabelPrint by using ajax request to this function RelatedUserAccessPermission

URL below I run it on browser to access function RelatedUserAccessPermission

https://localhost:7160/AddUserAccess?handler=RelatedUserAccessPermission

 public JsonResult OnGetRelatedUserAccessPermission(int UserId)
        {

            var UserAccess = _db.UserAccess.ToList();
            return new JsonResult(UserAccess);

        }

Data Returned from function OnGetRelatedUserAccessPermission

ModuleCode AccessRight UserId
1           1           1220
2           1           1220

so Based on user id

    if(modulecode=1 and accessright=1)
    
    then StockTake checkbox will be checked based on value =1
    
    if(modulecode=2 and accessright=1)
    
    then ShelfLabelPrint checkbox will be checked  based on value =2
    if(modulecode=3 and accessright=1)
    
    then Transfer checkbox will be checked based on value =3

on AddUserAccess.cshtml

<button id="FillCheckBox" type="submit" class="col-sm-1 btn btn-primary">Submit</button>
        <div class="form-group row">
            <label for="user-id" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">User ID</label>
            <div class="col-sm-3">
                <input id="useraccess-id" asp-for="UserAccess.UserId" type="text" class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;" />
            </div>
        </div>
        <input id="StockTake" type="checkbox" asp-for="UserAccess.MODULECODE" value="1">
        <label for="lblStockTake">Stock Take</label>

        <input id="ShelfLabelPrint" type="checkbox" asp-for="UserAccess.MODULECODE" value="2">
        <label for="lblShelfLabel">Shelf Label Print</label>

        <input id="Transfer" type="checkbox" asp-for="UserAccess.MODULECODE" value="3">
        <label for="lblTransfer" style="margin-right:5px;">Transfer</label>

for more details what I expect

How to fill checkboxes on razor Page

Exactly logic I need to Implement by ajax request

  <script type="text/javascript">
            $(document).ready(function () {
                $('#FillCheckBox').click(function () { 
                    //How to Make Ajax Request Fill CheckBoxes
if(modulecode=1 and accessright=1)
    
    then StockTake checkbox will be checked
    
    if(modulecode=2 and accessright=1)
    
    then ShelfLabelPrint checkbox will be checked 
    if(modulecode=3 and accessright=1)
    
    then Transfer checkbox will be checked


                    
                
            });
            });
        </script>

updated answer

<form method="post">
<button id="FillCheckBox" type="submit" class="col-sm-1 btn btn-primary">Submit</button>
<div class="form-group row">
<label for="user-id" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">User ID</label>
<div class="col-sm-3">
<input id="useraccess-id" asp-for="UserAccess.UserId" type="text" class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;" />
</div>
        </div>
        <input id="StockTake" type="checkbox" asp-for="UserAccess.MODULECODE" value="1">
        <label for="lblStockTake">Stock Take</label>
<input id="StockTake" type="hidden"  value="false" />
        <input id="ShelfLabelPrint" type="checkbox" asp-for="UserAccess.MODULECODE" value="2">
        <label for="lblShelfLabel">Shelf Label Print</label>

        <input id="Transfer" type="checkbox" asp-for="UserAccess.MODULECODE" value="3">
        <label for="lblTransfer" style="margin-right:5px;">Transfer</label>

        
       
        
    </form>

this is full code to my razor html form

if I leave method=post then it not working filling check boxes

if I remove method=post it working success and fill check box ajax working so whay this happen


Solution

  • For test, I change the checkbox asp-for="UserAccess.MODULECODE" into asp-for="UserAccess.ck" because there is ModuleCode property.

    Exactly logic I need to Implement by ajax request

    I have a work demo, you can refer to it, hope it can helps.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#FillCheckBox').click(function () {
                var id = $("#useraccess-id").val();     
                alert(id);
                $.ajax({
                    type: "Get",
                    url: "/AddUserAccess?Handler=RelatedUserAccessPermission",
                    data: { UserId: id },
                    success: function (result) {
                        for (i = 0; i < result.length; i++) 
                        {         
                            if(result[i].moduleCode == 1 & result[i].accessRight == 1)
                            { $("#StockTake").prop("checked", true); };
                            if (result[i].moduleCode == 2 & result[i].accessRight == 1)
                            { $("#ShelfLabelPrint").prop("checked", true); };
                            if (result[i].moduleCode == 3 & result[i].accessRight == 1) 
                            { $("#Transfer").prop("checked", true); };                      
                        };
                   },
                    failure: function (response) {
                        console.log(response);
                    }
                });
                    });
                    });
    </script>
    

    result: enter image description here

    Update

    if I remove method=post it working success and fill check box ajax working so whay this happen

    You are getting a 400 (Bad Request) response because the framework expects the RequestVerificationToken as part of the posted request.The framework uses this to prevent possible CSRF attacks. If your request does not have this information, the framework will return the 400 bad request. To make post work, please do some change as below:

    1.Change the post method like:

     public JsonResult OnPostRelatedUserAccessPermission(int UserId)
            {..}
    

    2.In the cshtml, add

    @Html.AntiForgeryToken()
    <form method="post">
    ...
    

    3.The Ajax request should send the anti-forgery token in request header to the server.

    beforeSend: function (xhr) {
         xhr.setRequestHeader("XSRF-TOKEN",
             $('input:hidden[name="__RequestVerificationToken"]').val());
     },
    

    4.In Program.cs, since the script sends the token in a header called XSRF-TOKEN, configure the antiforgery service to look for the XSRF-TOKEN header:

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

    5.Because use form with submit, but use ajax post userId, add event.preventDefault(); to avoid submit with null useId. Full code like:

    @section Scripts{
        <script type="text/javascript">
            $(document).ready(function () {
                $('#FillCheckBox').click(function (event) {
                    event.preventDefault();
                    var id = $("#useraccess-id").val();
                    alert(id);
                    $.ajax({
                        type: "post",
                        url: "/AddUserAccess?Handler=RelatedUserAccessPermission",
                        data: { UserId: id },
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
                        success: function (result) {
                            for (i = 0; i < result.length; i++) {
                                if (result[i].moduleCode == 1 & result[i].accessRight == 1) { $("#StockTake").prop("checked", true); };
                                if (result[i].moduleCode == 2 & result[i].accessRight == 1) { $("#ShelfLabelPrint").prop("checked", true); };
                                if (result[i].moduleCode == 3 & result[i].accessRight == 1) { $("#Transfer").prop("checked", true); };
                            };
                        },
                        failure: function (response) {
                            console.log(response);
                        }
                    });
                });
            });
        </script>
    }