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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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="#" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" data-movieId="34" class="movie">Delete Avengers</a>
<a href="#" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" 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>
Method 2
Depending on your code it could be as simple as:
$.post("/controller/method" + id);
Method 3
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) {
}
});
});
Method 4
Try This,
function (){
var url = '@Url.Action("SearchReoccurence", "SearchReoccurence", new { errormessage = "__msg__" })';
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0