简体   繁体   中英

Call C# method from javascript drag and drop event

I have the following jQuery which does drag and drop -

<script>
    $(function () {
        $(".draggable").draggable({
            helper: "clone"
        });
        $(".drag-div").droppable({
            accept: ".draggable",
            tolerance: "pointer",
            activeClass: "drop-here",
            hoverClass: "drop-here-hover",
            drop: function (event, ui) {
                $.fancybox({
                    href: '#add-quantity'                            
                });
            }
        });
    });
</script>

I need to be able to get the text value of what I have just dragged and dropped, then call a C# method which requires that parameter to alter a database table. How can I do this?

Thanks.

You need to create a web service method, you can do this in your same page and then use ajax to call this method. Here is a sample of this:

您需要使用Jquery Ajax,然后创建一个asmx或WebApi。

Are you using asp.net mvc? I think you could look for SignalR to do that.

So, if you think is to much, the simplest way could be to create one like ondrop.aspx and call it by some ajax method:

<script>
    $(function () {
        $(".draggable").draggable({
            helper: "clone"
        });
        $(".drag-div").droppable({
            accept: ".draggable",
            tolerance: "pointer",
            activeClass: "drop-here",
            hoverClass: "drop-here-hover",
            drop: function (event, ui) {

                var $div = $(ui.draggable); // here access the dragging div
                var param = $div.text();
                $.post('ondrop.aspx', { someparam: param }).done(function (e) {
                    console.log(e);
                });

                $.fancybox({
                    href: '#add-quantity'                            
                });
            }
        });
    });
</script>

See? In that point you have access to the dragging element, and you just have to select wich attribute you will need and then make a ajax call to some .aspx page. So you treat that page using Request.Form["someparam"]; and result a clean json from that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM