通过 AJAX 将多种类型的数据传递给 MVC C# 控制器

Passing multiple type of data via AJAX to MVC C# Controller

我正在使用 AJAX 从 Razor View 获取信息并将其发送到控制器

一切正常,但现在我需要传递一个数组 + 字符串,因此数据可能是:

// View - Javascript
var idkey = $('#idkey').val();
var selected = ['test1', 'test2', 'test3'];

$.ajax({
            type: 'POST',
            url: '/Adm/MyAction',
            traditional: true,
            data: { idkey: idkey, selected: selected }), ...

// Controller
[HttpPost]
public async Task<JsonResult> MyAction(string idkey, string[] selected)
{
  // Do something with the data passed on params
}

问题是......我无法在任何地方找到如何将两种不同类型的数据从 AJAX 发送到控制器

这个有效:

控制器:

public class HomeController : Controller
{
    [HttpPost]
    public string Index900(string theValue, string[] stringArray)
    {
        //put breakpoint here
        try
        {
            throw new Exception("this is the Value" + theValue);
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    public ActionResult Index()
    {
        return View();
    }

查看:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
        $(function () {
            $("#theBtn").click(function () {

                var idkey = $('#idkey').val();
                var selected = ['test1', 'test2', 'test3'];

                var theValue = $("#theInput").val();
                $.ajax({
                    url: "/Home/Index900",
                    dataType: 'text',
                    type: 'post',
                    contentType: 'application/json',
                    data: JSON.stringify({ theValue: idkey, stringArray: selected }),
                    success: function (result) {
                        alert(result);
                    },
                    error: function (data) {
                        alert("error...")
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div>
        <input type="button" id="theBtn" value="Click to start ajax" />
        <input type="text" id="idkey" value="Some Value" />
    </div>
</body>
</html>