Estoy usando AJAX para obtener la información de Razor View y enviarla al controlador
Todo funciona, pero ahora necesito pasar un Array + String para que los datos puedan ser:
// 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 }El problema es... No puedo encontrar en ninguna parte cómo enviar dos tipos diferentes de datos desde AJAX al controlador
esto funciona:
Controlador:
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(); }Vista:
@{ 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>