Patrik
Patrik

Reputation: 1129

Post Button in Grid

I have many products in grid (table).

Every row has an own button to delete and edit the product.

Now my question is: How can I identify after post message which table row was selected?

Best Regards

<table id="tbltraining" class="tblStyle">
<tr class="tblHearerRow">
    <th class="tblHearerCell" style="width:50px;">

    </th>
    <th class="tblHearerCell" style="width:50px;">

    </th>
    <th class="tblHearerCell" style="width:200px;">
        Name
    </th>
    <th class="tblHearerCell" style="width:100px;">
        Price
    </th>
    <th class="tblHearerCell">
        Actions
    </th>
</tr>
@foreach (var item in Model.Products)
{
    <tr class="tblRow" style="background-color:#c4cbf8">
        <td id="itemId" class="itemIdClass tblColumn">
            @Html.DisplayFor(modelItem => item.Id)
        </td>
        <td class="tblColumn" style="font-weight:bold;">
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td class="tblColumn">
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td class="tblColumn">
            <input type="button" value="Edit"
                   class="buttonEdit btnStyleOne" />
            <input type="button" value="Delete"
                   class="buttonDelete btnStyleOne" />
            <input type="button" value="Add Category"
                   class="buttonDelete btnStyleOne" />
        <td>
    </tr>

Upvotes: 0

Views: 365

Answers (2)

Khalid Abuhakmeh
Khalid Abuhakmeh

Reputation: 10839

Your best and most simple option is just to use the form tag. There is no restriction to how many forms you can have on a page.

<form action="@Url.Action("delete","products", new { id = item.ID })" method="POST">
     <button type="submit">Delete</button>
</form>

You can get really fancy and create a helper method or partial view, but that is basically all you need.

Extra points for using the HttpVerb DELETE.

Upvotes: 1

Shyju
Shyju

Reputation: 218732

Assuming that your View is to show a list of Products.

@foreach(var item in Model.Products)
{
  <div>
     <span>@item.ProductName</span>
     <span>@item.Price</span>

     @Html.ActionLink("Edit","Edit",new {@id=item.ID}) |
     @Html.ActionLink("Delete","Delete","Products",new {@id=item.ID},
                                                              new {@class="del"})
  </div>
}

ActionLink helper method will render anchor tag and clicking on which will issue a GET request. we do not want that for the DELETE operation. So we will bipass the click event in javascript and do a POST request asynchronously.

<script type="text/javascript">
$(function(){

  $("a.del").click(function(e){

     e.preventDefault();
     $.post($(this).attr("href"),function(res){
        // do something with the response
     });

  });

});
</script>

Upvotes: 1

Related Questions