Home > database >  take an id of a forEach method and pass it to asp-route-id
take an id of a forEach method and pass it to asp-route-id

Time:09-15

This is my View :

<a   id="check" asp-page-handler="Delete" asp-route-id=""  onclick="takeId()"> Delete Person</a>
 <table id="datatable" >
            <thead>
            <tr>
                <th>select</th>
                <th>id</th>
                <th>name</th>
            </tr>
            </thead>
            <tbody>
                @foreach (var item in @Model.MyViewModels)
                {
                    <tr>
                        <td><input type="checkbox"  id="box"  value="@item.Id"  /></td>
                        <td>@item.Id</td>
                        <td>@item.FullName</td>
                    </tr>
                }
            </tbody>
        </table>                

and this is my Index Model:

       public void OnGetDelete(long id)
        {
            _customerApplication.Delete(id);
           
        }

and my js codes:

function takeId() {

    var id = $("#box").attr('value');

    $("#check").attr('asp-route-id',id);
}

when i click on each item, i need to take the item's Id, and pass it to asp-route-id in "a" tag ,it seems that there are some wrongs in my codes, because when i select each item and click on "a" tag, The id returns the value 0

CodePudding user response:

The asp-route-id attribute is parsed by the anchor tag helper. Tag helpers are executed server-side to create html output that is sent to the browser. The asp- attributes are not included in the output because they have no meaning for the browser.

For example if you have this in your .cshtml file:

<a asp-page-handler="Delete" asp-route-id="1">Delete Person</a>

The anchor tag helper will parse the asp- attributes and generate the following html output:

<a href="/?handler=Delete&id=1">Delete Person</a>

The generated element is added to the html response that is sent to the browser. Now that the element is rendered in the browser (client-side), adding the asp- attribute with JavaScript will not have any effect.

enter image description here

  • Related