0

Newbie ALERT

Basically I have a web application that has a dropdown list. When you select an item in the drop-down list the table is drawn to show all the credentials that are tied to that drop-down option.

Problem: When running, everything functions properly except for the JavaScript piece that does not remove the line in the table, but deletes the record on the back-end. So once i refresh and go back to that credential type the one I deleted is gone.

I've tried a lot of different stuff, but i pretty new to JavaScript and C#, don't know if there is a better way of doing this. Probably supplied too much information but i rather too much than not enough! :)

Any help, tips, ideas are greatly appreciated.

Credential API Controller: Delete Function

[HttpDelete]
public IHttpActionResult DeleteCustomer(int id)
    {
        var credentialInDb = _context.Credentials.SingleOrDefault(c => c.Id == id);

        if (credentialInDb == null)
            return NotFound();

        _context.Credentials.Remove(credentialInDb);
        _context.SaveChanges();


        return Ok();
    }

Model for Credential

public class Credentials
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    [Required]
    [StringLength(255)]
    public string Username { get; set; }

    [Required]
    [StringLength(255)]
    public string Password { get; set; }


    public string Website { get; set; }


    public string Notes { get; set; }


    public CredentialType CredentialType { get; set; }

    [Display(Name = "Credential Type")]
    public int CredentialTypeId { get; set; }

}   

ViewModel for CredentialFormViewModel
This allows the selectedCredential variable for the page below

public class CredentialFormViewModel
{
    public IEnumerable<CredentialType> CredentialTypes { get; set; }
    public Credentials Credentials { get; set; }

    public int SelectedCredentialTypeId { get; set; }

}

View that displays the DataTable:

 @model Appp.ViewModels.CredentialFormViewModel


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Select a Credential Type</h2>
@Html.DropDownListFor(m => m.SelectedCredentialTypeId, new     SelectList(Model.CredentialTypes, "Id", "Name"), "Select Credential Type", new {     @class = "form-control", onchange = "SelectCredType()" })


<br/>
<table id="credentials" class="table table-bordered table-hover">
    <thead>
    <tr>
        <th>Credential</th>
        <th>Username</th>
        <th>Password</th>
        <th>Website</th>
        <th></th>     
    </tr>
    </thead>
    <tbody>
   </tbody>
</table>


@section scripts
{
<script>

    function SelectCredType() {
        var credId = $('#SelectedCredentialTypeId').val();
        if ($.fn.dataTable.isDataTable("#credentials")) {
            if (credId == "") {
                var table = $("#credentials").DataTable();
                table.destroy();

            } else {
                var table = $("#credentials").DataTable();
                table.destroy();
                SelectCredType();
            }
        } else {
            $(document)
                .ready(function() {
                        var table = $("#credentials")
                            .DataTable({
                                ajax: {
                                    url: "/api/credentials?credentialTypeId=" + credId,
                                    dataSrc: ""
                                },
                                columns: [
                                    {
                                        data: "name",

                                    },
                                    {
                                        data: "username"
                                    },
                                    {
                                        data: "password"
                                    },
                                    {
                                        data: "website"
                                    },
                                    {
                                        data: "id",
                                        render: function(data, type, credentials) {
                                            return "<button class='btn btn-primary btn-xs js-delete' data-credential-id=" + credentials.id + ">Delete</button>";
                                        }
                                    }
                                ]
                            });
                    }
                );
        }
    };


    $("#credentials")
        .on("click",
            ".js-delete",
            function() {
                var button = $(this);

                bootbox.confirm("Are you sure you want to delete this?",
                    function(result) {
                        if (result) {
                            $.ajax({
                                url: "/api/Credentials/" + button.attr("data-credential-id"),
                                method: "DELETE",
                                sucess: function() {
                                        table.row(button.parents("tr")).remove().draw();
                                }
                            });
                        }
                    });

            });
        </script>
}
Offir
  • 3,252
  • 3
  • 41
  • 73
Coberlin
  • 3
  • 1
  • 1
    Hi, first things first, [Java](https://en.wikipedia.org/wiki/Java_(programming_language)) != [JavaScript](https://en.wikipedia.org/wiki/JavaScript). I have a pending edit on your question that removes all references to Java. Secondly, are you able to give check whether your delete function throws any JavaScript error and report back? – Adrian Sanguineti Dec 14 '16 at 22:14
  • It also looks like you're referencing the `table` variable in your delete function when its no longer in scope (defined else where), which I would think to be your first problem. – Adrian Sanguineti Dec 14 '16 at 22:16
  • Thanks for your help Adrian. Thats what I was thinking but I was unable to reference it within the same function because it would duplicate the Delete function and it breaks that functionality.. but ill keep digging and look for some JavaScript errors – Coberlin Dec 15 '16 at 00:14
  • 1
    inside your delete function just use this on the first line of your success function: var table = $("#credentials").DataTable(); That should get the instance of your data table. Also I don't think you need to manually remove the row. Since you are refreshing data from the server just calling "draw" on the datatable instance should be enough since your deleted data won't be in the newly returned data set – Adrian Dec 15 '16 at 00:50

1 Answers1

0

First issue

Your JavaScript code does not work because the table variable is undefined within your delete function.

There are many ways you could approach to fix that. But first you will need to get your head around variable scopes in JavaScript.

Your simplest solution is to make table a globally-scoped variable that way you can access the instance from any function you create. So instead of defining it here:

 ... 
       $(document)
            .ready(function() {
                    var table = $("#credentials")
 ...

Move it up to the top of your script file:

var table;

function SelectCredType() {
    ...
        $(document)
            .ready(function() {
                    table = $("#credentials")
    ...
}

Now when you access it from your Delete function, it will be defined.

Note: I would also change the name of the table variable to something else as global variables in JavaScript will conflict with any script you import which can lead to a debugging nightmare. Best to name it something that will be most likely unique, eg. coberlinTable.

Second Issue

I don't know if you did a cut and past error, but you have misspelled success in your ajax Delete function.

Community
  • 1
  • 1
Adrian Sanguineti
  • 2,455
  • 1
  • 27
  • 29
  • As you obviously can tell I am very new to JavaScript and was piecing together tutorials as I am trying to learn but was stuck on this before I could move on. Your fix worked perfectly and I renamed the table as you suggested. I will read up more on variable scoping, thanks for the link! Thank you again!. – Coberlin Dec 15 '16 at 02:16