Home > OS >  Can not pass parameters from JQuery AJAX to controller
Can not pass parameters from JQuery AJAX to controller

Time:04-19

I am calling a method in JQuery like this

      var data = {
            'minAge': minAge,
            'MaxAge': maxAge,
            'ProductType': ProductType,
            'ProductSubject': ProductSubject,
            'ordering': '@Ordering.NotOrder',
            'Searchkey': "",
            'CatId': @Context.Request.Query["CatId"]
        }
       
        $.ajax({
            contentType: 'application/x-www-form-urlencoded',
            dataType: 'json',
            type: "POST",
            url: '/ApplyFilter',
            data: data,
            success: function (data) {
                // something happens
            }
        })

in Controller

    [HttpPost]
        public ViewComponentResult ApplyFilter(InvokeRequest invokerequest)
        {
            return ViewComponent("GetProducts",invokerequest);
        }


 public class InvokeRequest
    {
        public Ordering ordering { get; set; }
        public string Searchkey { get; set; }
        public string CatId { get; set; }        
        public int MinAge { get; set; }
        public int MaxAge { get; set; }
        public int ProductType { get; set; }
        public int ProductSubject { get; set; }
              
    }

but when I call the JQuery, the invoke request is always empty but in the view JavaScript is populated correctly, it seems the parameters cannot pass to the controller

CodePudding user response:

Your post request is probably not sending data correctly: I see you are telling ajax to encode data two diffents ways: contentType: 'application/x-www-form-urlencoded' and dataType: 'json' you should use one or another and if you tell json you should json.stringify(data) here: data: data,

also you can test your controller using curl.

CodePudding user response:

I have a test in my side and it worked for me. I test in an asp.net core 5 mvc project. And I created the same InvokeRequest as yours.

@{
    ViewData["Title"] = "Home Page";
}

    <button id="btn1">test</button>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
        var data = {
                'minAge': 1,
                'MaxAge': 10,
                'ProductType': 0,
                'ProductSubject': 0,
                'Searchkey': "",
                'CatId': "id1"
            }
        $("#btn1").click(function(){
            $.ajax({
                url:'https://localhost:44323/home/sendData',
                data:data,
                //dataType: 'json',//if we define the dataType, you need to make sure the response is a json
                type: "POST",
                success:function(da){
                    alert(da);
                }
            })
        })
    
    </script>
    
    
    //my controller
    [HttpPost]
    public string sendData(InvokeRequest req) {
        return "success";
    }
//if keep using `dataType: 'json',` then use follow action
[HttpPost]
public JsonResult sendData(InvokeRequest req) {
    var a = req.CatId;
    return Json(a);
}

enter image description here

CodePudding user response:

If you are using ASP.NET Core
Just add '[FromForm]'

public ViewComponentResult ApplyFilter([FromForm] InvokeRequest invokerequest)

Result image here



FromFormAttribute Class

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fromformattribute?view=aspnetcore-6.0

Model Binding in ASP.NET Core

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0

  • Related