Search code examples
c#asp.netmodel-view-controllerwebgrid

How to pass specific data from webgrid into MVC Controller using Javascript?


I'm trying to delete a specific row in my webgrid table using Javascript and Entity Framework. This is what i got so far:

enter image description here

The webgrid view works, I've added a (red cross) tag in the end for deleting this specific row.

HTML:

<div class="row">
        <div class="col-lg-12 d-flex align-items-stretch">
            @grid.Table(tableStyle: "table table-responsive table-striped table-bordered",
                columns: grid.Columns(
                  grid.Column(columnName: "ApiRedirectID", header: "ID", format:@<text><div class="edit" data-id="@item.ApiRedirectID" data-propertyname="ApiRedirectID">@item.ApiRedirectID</div></text>),
                  grid.Column(columnName: "ApiName", header: "Name", format:@<text><div class="edit" data-id="@item.ApiRedirectID" data-propertyname="ApiName">@item.ApiName</div></text>),
                  grid.Column(columnName: "CompanyID", header: "Company ID", format:@<text><div class="edit" data-id="@item.ApiRedirectID" data-propertyname="CompanyID">@item.CompanyID</div></text>),
                  grid.Column(columnName: "Company.CompanyName", header: "Company Name", format:@<text><div class="edit" data-id="@item.ApiRedirectID" data-propertyname="Company.CompanyName">@item.Company.CompanyName</div></text>),
                  grid.Column(columnName: "ApiURL2", header: "URL", format:@<text><div class="edit" data-id="@item.ApiRedirectID" data-propertyname="ApiURL2">@item.ApiURL2</div></text>),
                  grid.Column(columnName: "Delete", header: " ", format:@<a href="#" class="display delete-btn"><span class="glyphicon glyphicon-remove" style="color:red;"></span></a>)
          )
     )

        </div>
        <div class="col-lg-12 d-flex align-items-stretch">
            @grid.PagerList(mode: WebGridPagerModes.All, paginationStyle: "pagination pagination-small pagination-right")
        </div>
</div>

Javascript (what I came up with so far):

 $('.delete-btn').on("click", function () {

       //how to get specific row id here and pass it to my controller?     
 })

What I'm trying to achieve is that I pass the ApiRedirectID of the row I want to delete to Javascript and than to my MVC Controller.

Hope someone can help!

Thanks in advance!


Solution

  • Modify this line create an anchor tag to pass id and the best part is it will append id of each with anchor tag and you will get in controller directly

    (**In your case @item.Id From which you can find the record and delete it)**

    to the controller, so in the controller side, you will get id to remove it from DB.

    grid.Column(columnName: "Delete", header: " ", format:@<a href="Controller/action/id" class="display delete-btn"><span class="glyphicon glyphicon-remove" style="color:red;"></span></a>)