Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a controller method from Javascript

I am displaying a bunch of movies in a table, I am eventually deleting each movie through Javascript which hides the div.

I now want to delete the movie from the database as well, so what is the best way to call the controller method from the Javascript?

like image 344
James Avatar asked Jun 08 '12 13:06

James


People also ask

How do you call a controller method from HTML?

cs to determine the controller and action from the url. The default route is {controller}/{action}/{id} where the first two have defaults of "Home" and "Index", respectively, and the third is optional. You can change this if you want by adding/modifying the route set up.

How can we call controller method from JavaScript in asp net core?

The Controller's Action method is called using JavaScript XmlHttpRequest (XHR) AJAX request and the value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.


3 Answers

Have an HTTPPost action method to delete in your movie controller

[HttpPost]
public ActionResult Delete(int id)
{
  try
  {
    repo.DeleteMovie(id);
    return "deleted"
  }
  catch(Exception ex)
  {
    //Log errror
  }
  return "failed";
}

And in your View,

<a href="#" data-movieId="34" class="movie">Delete Avengers</a>
<a href="#" data-movieId="35" class="movie">Delete Iron Man</a>
<script type="text/javascript">
$(function(){

   $(".movie").click(function(e){
     e.preventDefault();
     $.post("@Url.Action("Delete","Movie")", { id : $(this).data("movieId")} ,function(data){
        alert(data);
     });
   });
});

</script>
like image 73
Shyju Avatar answered Nov 15 '22 00:11

Shyju


Depending on your code it could be as simple as:

$.post("/controller/method" + id);
like image 32
Tom Studee Avatar answered Nov 15 '22 01:11

Tom Studee


Try this: (Using jQuery Ajax)

$("#DeleteButtonID").on("click", function() {
    $.ajax(
    {
        type: "POST",
        page: 1,
        rp: 6,
        url: '@Url.Action("PopulateDataListWithHeader", "DataList")' + "?id=" + YOURID,
        dataType: "json",
        success: function(result) {

        },
        error: function(x, e) {

        }
    });
});
like image 40
Kapil Khandelwal Avatar answered Nov 14 '22 23:11

Kapil Khandelwal