Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

jquery - Basic AJAX example with ASP.NET MVC?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...