0

I want to delete record from table then update the table in MVC. Currently, I am able to delete the record from table but the table is not updating.I have written Script to update the partial but my script is not hitting.

Please suggest me how to do this?

Parent View

 <div class="col-md-2">
            @using (Html.BeginForm("HorseTracker", "HorseTracker", FormMethod.Post, new { @id = "CreateForm" }))
            {
                <div class="panel panel-default">

                    <div class="panel-body">
                        <div class="form-group">

                            @Html.LabelFor(m => m.HorseName, new { @class = "label-control" })
                            @Html.HiddenFor(m => m.HorseId)
                            @Html.TextBoxFor(m => m.HorseName)                       
                        </div>
                        <input type="submit" value="Save" class="btn btn-primary" />
                    </div>
                </div>

            }
        </div>

        <div id="partial" class="col-md-8">

Partial View

<div class="panel panel-default">

    <div class="panel-body">
        <table class="table">
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.HorseName)
                </th>

                <th>
                    @Html.DisplayName("Action")
                </th>

            </tr>

            @foreach (var item in Model)
            {
                <tr>
                    <td class="hidden">
                        @item.HorseId
                    </td>

                    <td>
                        @item.HorseName
                    </td>


                    <td>                      
                        @Ajax.ActionLink("Delete", "Delete", "HorseTracker", new {TrackerId = @item.TrackerId, AccId=item.AccId,UserId=item.UserId, @id = "DeleteRecord" }, new AjaxOptions
                   {
                       HttpMethod = "Post",
                       Confirm = "Are you sure you want to delete this record?"
                   }, null)                
                    </td>
                </tr>
            }

        </table>

    </div>
</div>

Controller Method

[HttpPost]
public PartialViewResult Delete(int TrackerId, int AccId, int UserId)
{
         ClsHorseTracker model = new ClsHorseTracker();
        var username = User.Identity.Name;
        var user = context.Users.SingleOrDefault(u => u.UserName == username);
        model.AccId = user.AccountID;
        model.UserId = user.Id;
        horseTrackerDetails.HorseTrackerDelete(TrackerId);

   return PartialView("_pHorseTrackerDetails", horseTrackerDetails.HorseTrackerList(model));
}

Script

 $(document).ready(function () {
        var url = '@Url.Action("Delete", "HorseTracker")';
        $(document).click('#DeleteRecord', function () {
            debugger;
              if (!$(this).valid()) {
                return;
            }
              $.post(url, $(this).serialize(), function (response) {
                  if (response) {
                      debugger;
                      $('#partial').html(response);
                      $('#CreateForm').get(0).reset();
                  }
              });
               return false;
           })
    })
Frame
  • 95
  • 9
  • The code you shared will throw a compile error as your `Delete` method is not returning anything! Please post correct code – Shyju Aug 21 '18 at 00:56
  • Your POST method does not even compile (your not returning anything). But there is no need to return a partial view anyway - you can just delete the row from the DOM –  Aug 21 '18 at 00:57
  • You aslo have invalid html (duplicate id attributes in your link), and why are you using `@Ajax.ActionLink() when you are also using `$.ajax()` –  Aug 21 '18 at 00:58
  • Have a look at the `$('.delete').click(function() {` function in [this answer](https://stackoverflow.com/questions/40539321/a-partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892) for what you should be doing (and your `if (!$(this).valid()) {` is pointless and can be removed) –  Aug 21 '18 at 01:00
  • `$(document).click('#DeleteRecord', function () { ... })` => sounds like you should do this: `$('#DeleteRecord').on('click', function () { ... })`. Also `Ajax.ActionLink` is pointless because you're already have `$.post` for POST method. – Tetsuya Yamamoto Aug 21 '18 at 01:02
  • @StephenMuecke, I have updated controller code. Sorry, by mistake, return got removed. – Frame Aug 21 '18 at 01:30
  • @Shyju, I updated controller method. – Frame Aug 21 '18 at 01:31
  • Now read the link I gave you. You have multiple errors with your code (and `$(this).serialize()` makes no sense - its a `` tag!) –  Aug 21 '18 at 01:32
  • @StephenMuecke, I am reading it now. Please give me some time. I will implement it and will see. – Frame Aug 21 '18 at 01:34
  • @StephenMuecke, Can you please provide answer for this. – Frame Aug 21 '18 at 02:01
  • @StephenMuecke, can you please invite me on chat. – Frame Aug 21 '18 at 02:13
  • Go to the [other chat](https://chat.stackoverflow.com/rooms/177853/discussion-between-stephen-muecke-and-mvc) –  Aug 21 '18 at 02:14

1 Answers1

2

There are multiple issues with your code. To mention a few

  1. You have multiple links with the same id attribute which is invalid html
  2. You use Ajax.AcionLink() but then cancel it and use $.post() to submit (which makes no sense)
  3. A link is not a form so checking if (!$(this).valid()) { makes no sense
  4. Your not sending any data to the POST method ($(this).serialize() is serializing the <a> element which does not contain any form controls so there is nothing to serialize)

There is no reason to return a partial view of the updated table (and its unnecessary extra overhead to do so). Instead just delete the row associated with the link if the Delete action was successful (which you signal by returning a JsonResult).

Change the loop code to

@foreach (var item in Model)
{
    <tr>
        <td class="name">@item.HorseName</td>
        <td><a href="#" class="delete" data-id="@item.TrackerId">Delete</a></td>
    </tr>
}

and add the following script

var url = '@Url.Action("Delete", "HorseTracker")';
$('.delete').click(function() {
    var id = $(this).data('id');
    var row = $(this).closest('tr');
    var name = row.find('.name').text();
    if (window.confirm('Are you sure you want to delete ' + name + '?')) {
        $.post(url, { id: id }, function(response) {
            if (response) {
                row.remove(); // remove the row from the DOM
            }
        }).fail(function(response) {
            .... // an exception was thrown on the server (display error message?)
        });
    }
});

Then modify your POST method to

[HttpPost]
public PartialViewResult Delete(int id)
{
    horseTrackerDetails.HorseTrackerDelete(id);
    return Json(true);
}