James
James

Reputation: 2999

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?

Upvotes: 7

Views: 82578

Answers (5)

Yaron Binder
Yaron Binder

Reputation: 125

A bit late for the party, but maybe it will help someone. For me, on ASP.NET MVC 5 this work wonderfully:

Client jQuery side

let data1 = 'some text';
let data2 = 'some other text';

$.post('ControllerName/MethodName', { field1: data1, field2: data2 }, 
    function(response) {
    // Do something here with the data return from the controller
    }
});

field1 and field2 needed to be the exact same name written in your method fields.

It's best to user JsonResult as the return type from your controller's method and parse it with Json() method.

Controller's method example

[HttpPost]
public JsonResult Method(string field1, string field2)
{
    // Do something here with the data sent from the jQuery client side
    ClassExample example = new();
    return Json(example);
}

Upvotes: 0

Tom Studee
Tom Studee

Reputation: 10452

Depending on your code it could be as simple as:

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

Upvotes: 5

GoviNd Gopi
GoviNd Gopi

Reputation: 1

Try This,

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

Upvotes: 0

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16144

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) {

        }
    });
});

Upvotes: 4

Shyju
Shyju

Reputation: 218932

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>

Upvotes: 6

Related Questions