views:

2379

answers:

4

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?

A: 

I don't know about simple, but there's a full MVC application that uses MVC, including jQuery and AJAX, posted at http://www.codeplex.com/nerddinner and a working version of the application at http://www.nerddinner.com.

tvanfosson
A: 

You can also found a tutorial here, it's part of 7 iterations on the http://asp.net/learn/mvc site

find it here: http://www.asp.net/learn/mvc/tutorial-32-vb.aspx

Peter
+10  A: 

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;
    }
}
Johannes Setiabudi
Why in your example code above wouldn't you just return CheckPermission(); ?
Phil.Wheeler
because you may want to do some extra logic/action if CheckPermission returns true - see the // flag post area
Johannes Setiabudi