简体   繁体   中英

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

I'm using AJAX to get the info from the Razor View and send it to controller

Everything is working but now I need to pass an Array + String so the data could be:

// 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
}

The issue is... I can't find anywhere how to send two different types of data from AJAX to controller

this works:

Controller:

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();
    }

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM