James James - 1 year ago 76
ASP.NET (C#) Question

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?

Answer Source

Have an HTTPPost action method to delete in your movie controller

public ActionResult Delete(int 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">

     $.post("@Url.Action("Delete","Movie")", { id : $(this).data("movieId")} ,function(data){

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download