How to call a controller method from Javascript

I show a bunch of movies in a table, I end up deleting every movie through Javascript that hides the div.

Now I want to delete a movie from the database, so what's the best way to call the controller method from Javascript?

+5
source share
4 answers

You have an HTTPPost method to delete in your controllermovie

[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>
+4
source

Depending on your code, this may be as simple as:

$.post("/controller/method" + id);
+3
source

Try the following: (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) {

        }
    });
});
+1
source

Try it,

function (){
   var url = '@Url.Action("SearchReoccurence", "SearchReoccurence", new { errormessage = "__msg__" })';
}
0
source

All Articles