如何使用Javascript将特定数据从Webgrid传递到MVC Controller?

时间:2019-05-08 09:58:16

标签: c# asp.net model-view-controller webgrid

我正在尝试使用Javascript和Entity Framework删除Webgrid表中的特定行。这就是我到目前为止所得到的:

enter image description here

webgrid视图有效,最后我添加了一个(红叉)标记,用于删除此特定行。

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(到目前为止我想出了什么):

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

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

我要实现的目标是,将要删除的行的ApiRedirectID传递给Javascript,而不是MVC Controller。

希望有人可以提供帮助!

谢谢!

2 个答案:

答案 0 :(得分:1)

修改此行 创建一个锚标记以传递ID,最好的部分是它将在每个ID后面附加锚标记,您将直接进入控制器

(**对于您的@ item.Id,可以从中找到记录并删除记录)**

对控制器, 因此在控制器端,您将获得ID将其从数据库中删除。

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>)

答案 1 :(得分:1)

假设每一行都是<tr>,则可以执行类似操作。

$('.delete-btn').on("click", "body", function () {
        var $row = $(this).closest('tr');
        var rowid = $row.find('[data-propertyname="ApiRedirectID"]');
        $.ajax({
          method: "POST",
          url: "controller/deleterow",
          data: { id: rowid }
        })
          .done(function( msg ) {
            alert( "Row Deleted!" );
      });
 });