SmartPro

CSharp · Mvc

Model

using System;
using System.ComponentModel.DataAnnotations;

namespace HelloWorldMvcApp
{
	public class SampleViewModel
	{
		
	}
}

View

<!DOCTYPE html>

    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index5</title>
		<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
         <script>
            $(function () {
            	$('#theButton').click(function () {
					var stockValues = $(".stockvalue");
			        var theArray = [];
			
			         $.each(stockValues, function (index, aValue) {
			              theArray.push(aValue.value);
			        })
			 
			 	$.ajax({
			    	type: "POST",
			        url: '@Url.RouteUrl(new{ action="MyAjaxCallMethodPassingArray", controller="Home"})',
			        traditional: true,
			        data: { 'arrayOfValues': theArray },
					dataType: "text",
			        success: function(data) {
						$("#showAnswer").html(data);
			        }
			    });
              })
            })
        </script>
    </head>
    <body>
        <div>
		    <div id="showAnswer"></div>
            <input type="text" class="stockvalue" />
            <input type="text" class="stockvalue" />
            <input type="text" class="stockvalue" />
            <input type="text" class="stockvalue" />
            <input type="button" value="Go" id="theButton" />
        </div>
    </body>
    </html>

Controller

using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace HelloWorldMvcApp
{
	public class HomeController : Controller
	{
		[HttpGet]
		public ActionResult Index()
		{
			 return View();
		}


		[HttpPost]
        public string MyAjaxCallMethodPassingArray(String[] arrayOfValues)
        {
            //put a breakpoint here to see the arrayOfValues
			//https://stackoverflow.com/questions/13426463/convert-an-array-to-string
			return string.Join(",", arrayOfValues);
          
        }
    }
}
;