Nils Anders
Nils Anders

Reputation: 4410

Reusable jQuery delete function

I using the following function to delete a row in a table

//delete individual row
jQuery('.stdtable img.delete').click(function(){
    var c = confirm('Continue delete?');
    if(c) jQuery(this).parents('tr').fadeOut(function(){ 
        jQuery(this).remove();
    });
    return false;
});

This code is in a separate js file and is common to all pages. Now I would like to add an Ajax action that deletes the row from the database. But depending on which page I'm on, it must call different controller.

Example: Product page must call delete in ProductController ProductGroup page must call delete in ProductGroupController

How to handle this?

Upvotes: 2

Views: 385

Answers (3)

toy
toy

Reputation: 12141

If I understand your question right, you want to click the image with class delete to make a call to delete that row in the database. The simplest solution would be

<img data-rowid="1" src="something.jpg"/>

jQuery('.stdtable img.delete').click(function(e){
    e.preventDefault();
    var c = confirm('Continue delete?');
    var that = this;
    if(c) {
        var id = this.data("rowid");
        jQuery.ajax({ url : "/resource/"+id, method : "DELETE" 
              statusCode: {
                 200: function() {
                       jQuery(that).parents('tr').fadeOut(function(){ 
                            jQuery(that).remove();
                       });
                 }
              }});

    }
    return false;
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

If you need some method of defining which controller to call, you could put a data attribute on the table. Something like this:

<table class="stdtable" data-remove-url="@Url.Action("DeleteRow", "MyController")">
    <tr data-id="1">
        AAA
        <img class="delete" src="foo.jpg" />
    </tr>
    <tr data-id="2">
        BBB
        <img class="delete" src="foo.jpg" />
    </tr>
 </table>

Then in your jQuery you can get this value as the url parameter of your request, along with the id to delete.

jQuery('.stdtable img.delete').click(function(e) {
    e.preventDefault();
    if (confirm('Continue delete?')) {
        var $el = $(this);
        var $tr = $el.closest('tr');
        var url = $el.closest('table').data('remove-url');
        var id = $tr.data('id');

        $tr.fadeOut(function() { 
            $el.remove();
            $.post(url, { rowId = id }); // do the delete on the server 
        });
    }
});

Upvotes: 5

Kenny Tordeur
Kenny Tordeur

Reputation: 212

You could add a custom attribute to your table or row with contains the url off the controller you need to call. In your method you can read this custom attribute to get the url of your controller.Look here for the JQuery attr methode.

Upvotes: 1

Related Questions