我正在像這樣在 JQuery 中呼叫一個方法
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
}
})
在控制器中
[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; }
}
但是當我呼叫 JQuery 時,呼叫請求始終為空,但在視圖中正確填充了 JavaScript,似乎引數無法傳遞給控制器
uj5u.com熱心網友回復:
您的發布請求可能未正確發送資料:我看到您告訴 ajax 以兩種不同的方式編碼資料: contentType: 'application/x-www-form-urlencoded' 和 dataType: 'json' 你應該使用一種或另一種,如果你告訴 json 你應該在這里 json.stringify(data): data: data,
您也可以使用 curl 測驗您的控制器。
uj5u.com熱心網友回復:
我身邊有一個測驗,它對我有用。我在一個 asp.net core 5 mvc 專案中進行測驗。我創造了InvokeRequest和你一樣的東西。
@{
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);
}

uj5u.com熱心網友回復:
如果您使用的是 ASP.NET Core
只需添加 '[FromForm]'
public ViewComponentResult ApplyFilter([FromForm] InvokeRequest invokerequest)
結果圖在這里
FromFormAttribute 類
https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fromformattribute?view=aspnetcore-6.0
ASP.NET Core 中的模型系結
https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459880.html
標籤:C# jQuery 阿贾克斯 asp.net-mvc asp.net-core-mvc
上一篇:GraphQL查詢為空
