用jQuery调用C#方法 [英] Calling a C# method with jquery

查看:121
本文介绍了用jQuery调用C#方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在按钮上单击时使用jQuery调用方法.这是我到目前为止的事情:

I am trying to call a method with jQuery on a button click.This is waht I have so far:

$("a.AddToCart").click(function () {
            var link = document.URL;

            $.ajax({
                 type:"POST",
                 url: "/Account/AddToCartHack",
                 data: {url : link},
                 contentType: "application/json; charset=utf-8",
                 dataType: "json"
            });
        });


[WebMethod]
    public void AddToCartHack(string url)
    {
        GeneralHelperClass.URL = url;
    }

我要在这里做的是,当我单击类添加到购物车的链接时,我想调用方法AddToCartHack并将当前URL作为参数传递给它. 我肯定做错了,因为似乎未调用AddToCartHack.

What I am trying to do here is when I click the link with class add to cart I want to call the method AddToCartHack and pass it the curent URL as a parameter. I must be doing something wrong because it seems that AddToCartHack is not being called.

我在做什么错了?

推荐答案

您的代码有很多问题,我不知道从哪里开始.因此,让我们与您进行一次交互式重构会话(如果您不在乎我的评论,而只想查看最终的和推荐的解决方案,只需在答案末尾向下滚动即可.)

There are quite a lot of issues with your code, I don't know where to start. So let's conduct an interactive refactoring session with you (if you don't care about my comments but just want to see the final and recommended solution, just scroll down at the end of answer).

第一:您似乎并没有通过从.click()事件处理程序中返回false来取消锚点的默认操作.否则,您实际上是在让浏览器执行锚的默认操作(如您所知,锚是重定向到href属性所指向的url.因此,您的AJAX调用永远不会时间来执行,因为浏览器已经离开页面并且不再运行任何脚本).因此,请从处理程序中返回false,以使您的AJAX脚本可以执行并停留在同一页面上:

First: you don't seem to be canceling the default action of the anchor by returning false from the .click() event handler. By not doing this you are actually leaving the browser perform the default action of the anchor (which as you know for an anchor is to redirect to the url that it's href attribute is pointing to. As a consequence to this your AJAX call never has the time to execute because the browser has already left the page and no more scripts are ever running). So return false from the handler to give your AJAX script the possibility to execute and stay on the same page:

$("a.AddToCart").click(function () {
    var link = document.URL;

    $.ajax({
        type:"POST",
        url: "/Account/AddToCartHack",
        data: {url : link},
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });

    return false;
});

第二:您已指定contentType: 'application/json'请求标头,但根本不发送任何JSON.您正在发送application/x-www-form-urlencoded请求,这是jQuery的默认请求.因此,请摆脱这种无意义的参数:

Second: You have specified contentType: 'application/json' request header but you are not sending any JSON at all. You are sending a application/x-www-form-urlencoded request which is the default for jQuery. So get rid of this meaningless parameter in your case:

$("a.AddToCart").click(function () {
    var link = document.URL;

    $.ajax({
        type:"POST",
        url: "/Account/AddToCartHack",
        data: {url : link},
        dataType: "json"
    });

    return false;
});

第三:您已指定服务器端代码将返回JSON(dataType: 'json'),但服务器端代码完全不返回任何内容.这是一个无效的方法.在ASP.NET MVC中,您所谓的C#方法有一个名称.这称为控制器操作.并且在ASP.NET MVC控制器中,操作返回的是ActionResults,而不是void.因此,请解决您的contoller操作.还摆脱[WebMethod]属性-在ASP.NET MVC中不再使用

Third: You have specified that your server side code will return JSON (dataType: 'json') but your server side code doesn't return anything at all. It's a void method. In ASP.NET MVC what you call C# method has a name. It's called a controller action. And in ASP.NET MVC controller actions return ActionResults, not void. So fix your contoller action. Also get rid of the [WebMethod] attribute - that's no longer to be used in ASP.NET MVC

public class AccountController: Controller
{
    public ActionResult AddToCartHack(string url)
    {
        GeneralHelperClass.URL = url;
        return Json(new { success = true });
    }
}

第四:您已将url硬编码为javascript中的控制器操作,而不是使用服务器端帮助程序来生成此url.这样做的问题是,如果您在虚拟目录中的IIS中部署应用程序,则代码将中断.不仅如此-如果您决定在Global.asax中修改路由模式,则由于URL不再为{controller}/{action},因此您将不得不修改所有脚本.我建议您解决此问题的方法是使用不引人注目的AJAX.因此,您只需使用HTML帮助器即可生成锚点:

Fourth: you have hardcoded the url to the controller action in your javascript instead of using server side helpers to generate this url. The problem with this is that your code will break if you deploy your application in IIS in a virtual directory. And not only that - if you decide to modify the pattern of your routes in Global.asax you will have to modify all your scripts because the url will no longer be {controller}/{action}. The approach I would recommend you to solve this problem is to use unobtrusive AJAX. So you would simply generate the anchor using an HTML helper:

@Html.ActionLink(
    "Add to cart", 
    "AddToCartHack", 
    "Account", 
    null, 
    new { @class = "AddToCart" }
)

然后毫不客气地AJAXify这个锚点:

and then unobtrusively AJAXify this anchor:

$('a.AddToCart').click(function () {
    var link = document.URL;

    $.ajax({
        type: 'POST',
        url: this.href,
        data: { url : link }
    });

    return false;
});

第五:您似乎在.click()处理程序中使用了某些document.URL变量.看起来某些全局javascript变量必须已在其他位置定义.不幸的是,您没有显示代码中定义此变量的部分,也没有说明为什么使用它,因此我无法真正提出一种更好的方法来执行此操作,但我确实感到它存在问题.还是哦,等等,这应该是当前的浏览器网址吗???是的,因此您应该使用window.location.href属性.就是这样:

Fifth: You seem to be employing some document.URL variable inside your .click() handler. It looks like some global javascript variable that must have been defined elsewhere. Unfortunately you haven't shown the part of the code where this variable is defined, nor why is it used, so I cannot really propose a better way to do this, but I really feel that there's something wrong with it. Or oh wait, is this supposed to be the current browser url??? Is so you should use the window.location.href property. Just like that:

$('a.AddToCart').click(function () {
    $.ajax({
        type: 'POST',
        url: this.href,
        data: { url : window.location.href }
    });

    return false;
});

甚至更好,使其成为原始锚点的一部分(最终和推荐的解决方案):

or even better, make it part of the original anchor (Final and recommended solution):

@Html.ActionLink(
    "Add to cart", 
    "AddToCartHack", 
    "Account", 
    new { url = Request.RawUrl }, 
    new { @class = "AddToCart" }
)

然后简单地:

$('a.AddToCart').click(function () {
    $.ajax({
        type: 'POST',
        url: this.href
    });

    return false;
});

现在,这比起初的情况要好得多.现在,即使页面上禁用了javascript,您的应用程序也可以正常工作.

Now that's much better compared to what we had initially. Your application will now work even with javascript disabled on the page.

这篇关于用jQuery调用C#方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆