简体   繁体   English

使用 JQuery Ajax 和 ASP.Net Mvc 的正确模式是什么?

[英]What is the right pattern for using JQuery Ajax and ASP.Net Mvc?

I'm very new to both the Mvc framework as well as JavaScript and JQuery.我对 Mvc 框架以及 JavaScript 和 JQuery 都很陌生。 I'm trying to understand the right way to structure Ajax calls.我试图了解构建 Ajax 调用的正确方法。

Let's say I have a Vote Up button similar to what you see on StackOverflow.假设我有一个类似于您在 StackOverflow 上看到的Vote Up按钮。 When the user clicks it I need to update the vote count in the database and return the new value to the UI.当用户单击它时,我需要更新数据库中的投票计数并将新值返回给 UI。 Currently I am achieving this by having an action called VoteUp on the PostsController which takes an int postID as a parameter.目前,我具有称为操作实现这一VoteUpPostsController这需要一个int postID作为参数。

public PostsController : Controller
{
    public ActionResult VoteUp(int postId)
    {
        //Increment Post Vote Count
        return Json(voteCount); //Return just the new vote count as a JSon result.
    }
}

I'm then calling this method via ajax by invoking the url " http://example.com/posts/voteUp?postId=5 ".然后我通过 ajax 调用这个 url “ http://example.com/posts/voteUp?postId=5 ”来调用这个方法。 I then return an JSon ActionResult with the new value to update the UI with.然后我返回一个带有新值的 JSon ActionResult 来更新 UI。

Is this the right way to implement this?这是实现这一点的正确方法吗? Again, I'm totally new to both javascript and jquery.同样,我对 javascript 和 jquery 都是全新的。 I'm used to doing everything as click event handlers in asp.net webforms.我习惯于在 asp.net webforms 中做所有事情作为点击事件处理程序。 Any guidance would be appreciated.任何指导将不胜感激。

Yes, it sounds like you've got it about right.是的,听起来你说得对。

Note, however, that if you change postId to Id, then you could call with a URL like:但是请注意,如果将 postId 更改为 Id,则可以使用如下 URL 进行调用:

http://example.com/posts/voteUp/5 http://example.com/posts/voteUp/5

(With the default routing.) It's a question of personal preference. (使用默认路由。)这是个人喜好的问题。

I would approach this using jQuery and JsonResult Controller.我会使用 jQuery 和 JsonResult 控制器来解决这个问题。 Your jQuery code would call the JsonResult which would pass the pertinent information off to the model code to handle adding a new vote.您的 jQuery 代码将调用 JsonResult,它将相关信息传递给模型代码以处理添加新投票。 I wrote a brief tutorial on similar concepts which is available at http://www.dev102.com/2008/08/19/jquery-and-the-aspnet-mvc-framework/我写了一个关于类似概念的简短教程,可在http://www.dev102.com/2008/08/19/jquery-and-the-aspnet-mvc-framework/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM