Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic AJAX example with ASP.NET MVC?

Tags:

I'm in the process of making a demo ASP.NET MVC app for educational purposes.

I have an image/link that flags a post as offensive. I would like to request from the server via AJAX to flag offensive and check to make sure that the user has this ability.

If the user does, then I want to flag the post as offensive in the database and return that the flag went through. If the user ends up NOT having the right to flag items then I would like to return a negative message to the client so I can popup a nice jQuery box stating that it didn't go through.

I'm trying to do this all without a full postback/refresh.

Does anyone have any links to examples of simple AJAX requests being made with MVC?

like image 921
Mithrax Avatar asked Apr 19 '09 06:04

Mithrax


People also ask

What is AJAX explain with example?

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.


1 Answers

It is actually pretty easy with jQuery. Let's say your link is something like this:

<a href="javascript:flagInappropriate(<%=Model.PostId%>);">Flag as inappropriate</a> 

Create a javascript to call the action in your controller to check and flag as necessary:

function flagInappropriate(postId) {     var url = "<CONTROLLER>/<ACTION>/" + postId;     $.post(url, function(data) {         if (data) {             // callback to show image/flag         } else {             // callback to show error/permission         }     }); } 

In you action method in your controller will probably look like this:

[AcceptVerbs("POST")] public bool FlagAsInappropriate(int id) {     // check permission     bool allow = CheckPermission();      // if allow then flag post     if (allow) {         // flag post          return true;     } else {         return false;     } } 
like image 166
Johannes Setiabudi Avatar answered Oct 17 '22 13:10

Johannes Setiabudi