ASP.Net Core 2 Razor AJAX GET带参数?

问题描述 投票:0回答:3

如何在我的ASP.Net Core 2 Razor应用程序中使用我想要传递给接收函数的参数进行AJAX GET-Request。

例如,我的HTML中有一个Select-Field。根据选择的值,我希望收到值列表。为此我用这种方式写了一个AJAX-GET-Request。

$.ajax({
    type: 'GET',
    url: '/Index?handler=Test2',
    contentType: 'json',
    success: function (result) {
        console.log('Data received: ');
        console.log(result);
    }
});

所以这个电话几乎完美无缺。它在我的Code-Behind-Page(Index.cshtml.cs)中调用OnGetTest2()。我的OnGetTest2()看起来像:

[HttpGet]
public IActionResult OnGetTest2(string id)
{
     // Some code logic to get the needed values i want to post back
     Console.WriteLine("Received id: " + id);
     return new JsonResult(9999); // e.g. 9999 as return value
}

但我坚持如何将我的Select-Element的选定选项的值与我上面的AJAX-Call传递给我的OnGetTest2()-Function。我怎样才能让它发挥作用?实际上我会收到“9999”,所以AJAX-Call正在工作,但我需要传递所选的值OnGetTest2()-Function。

jquery ajax razor asp.net-core-mvc
3个回答
1
投票

有两种基本方法可以做到这一点。

选项1:使用查询字符串。你的ajax基本上就是你拥有的,你设置一个url变量handler等于“Test2”。在控制器中使用Request.Query["handler"]来获取值。

[HttpGet]
public IActionResult OnGetTest2()
{
    var id = Request.Query["handler"];
    // ... more stuff

}

选项2:路线属性。路线属性真棒!将ajax中的url更改为url = '/Index/Test2',然后在控制器中使用它:

[HttpGet, Route("index/{id}")]
public IActionResult OnGetTest2(string id)
{
    // id already has the value in it
    // ... do stuff

}

如果你想要一个字符串以外的东西,比如int,就可以使用这样的东西。

[HttpGet, Route("index/{id:int}")]
public IActionResult OnGetTest2(int id)
{

    // ... do stuff

}

0
投票

首先获取Select-Field的值

var SelectFieldValue =  $("#Select-Field-ID").val();

然后通过ajax调用将其发送到操作:

 $.ajax({
    type: 'GET',
    url: '/Index?id=' + SelectFieldValue,
    contentType: 'json',
    success: function (result) {
        console.log('Data received: ');
        console.log(result);
    }
});

0
投票

您需要声明一个设置为等于所选项的变量,而不是将字符串“Test2”作为参数发送。

var e = document.getElementById("ddl");
var item= e.options[e.selectedIndex].value;

或者JQuery

var item = $('#ddl').val();

然后你可以通过AJAX发送

$.ajax({
   type: 'GET',
   url: '/Index?id=' + item,
   contentType: 'json',
   success: function (result) {
    console.log('Data received: ');
    console.log(result);
   }
});
© www.soinside.com 2019 - 2024. All rights reserved.