jQuery ASP.NET MVC 的基本 AJAX 示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/764965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:45:11  来源:igfitidea点击:

Basic AJAX example with ASP.NET MVC?

jqueryajaxasp.net-mvc

提问by Mithrax

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

我正在制作用于教育目的的演示 ASP.NET MVC 应用程序。

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.

我有一个图片/链接,将帖子标记为具有攻击性。我想通过 AJAX 从服务器请求标记攻击性并检查以确保用户具有此能力。

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.

如果用户这样做,那么我想在数据库中将帖子标记为具有攻击性,并返回该标记通过的信息。如果用户最终无权标记项目,那么我想向客户端返回一条负面消息,以便我可以弹出一个漂亮的 jQuery 框,说明它没有通过。

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?

有没有人有任何链接到使用 MVC 发出的简单 AJAX 请求的示例?

采纳答案by Johannes Setiabudi

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

使用 jQuery 实际上很容易。假设您的链接是这样的:

<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:

创建一个 javascript 来调用控制器中的操作以根据需要进行检查和标记:

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:

在你的控制器中的 action 方法可能看起来像这样:

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

回答by Cubicle.Jockey

Here is using @Ajax object example. More simply it is @Ajax.ActionLink.

这是使用@Ajax 对象的示例。更简单的是@Ajax.ActionLink。

http://ovisdevelopment.com/davisisms/?p=82&preview=true&preview_id=82&preview_nonce=32c77db2e4

http://ovisdevelopment.com/davisisms/?p=82&preview=true&preview_id=82&preview_nonce=32c77db2e4