Calling a C# method with jquery

后端 未结 5 1540
旧时难觅i
旧时难觅i 2021-02-09 18:00

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 =         


        
相关标签:
5条回答
  • 2021-02-09 18:44

    place script method this way as shown below

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    
    0 讨论(0)
  • 2021-02-09 18:46

    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).

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

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

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

    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" }
    )
    

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

    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" }
    )
    

    and then simply:

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

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

    0 讨论(0)
  • 2021-02-09 18:50

    Add Success and error function to check your ajax functionality

           ...
    
    
           $.ajax({
                     type:"POST",
                     url: "/Account/AddToCartHack",
                     data: {url : link},
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                   success: function(){
                     alert('success');
                    },
                  error:function(){ 
                      alert('error');
                    }
                });
            ....
    
    0 讨论(0)
  • 2021-02-09 18:55
    $(document).ready(function () {
    
        $.ajax({
    
            url: "Testajax.aspx/GetDate",
            data: "f=GetDate",
            cache: false,
            success: function (content) {
                $('#tableData').append('My Dear Friend');
                alert(content);
    
            },
            failure: function (response) {
                alert("no data found");
            }
    
    
        });
    });
    

    0 讨论(0)
  • 2021-02-09 19:01

    If this is Asp.Net webforms you will need to make the webmethod static or the method cannot be accessed through JavaScript.

    0 讨论(0)
提交回复
热议问题