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
3
Answers
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.
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.If you are using ASP.NET Core
Just add ‘[FromForm]’
Result image here
FromFormAttribute Class
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fromformattribute?view=aspnetcore-6.0
Model Binding in ASP.NET Core
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0