1

I'm using ASP.NET MVC w/ Views.

This is a two part question.

I've got a C# method that returns an array of numbers. These values are then sent to a javascript function which calculates and creates random numbers. The way I passed the values from C# to javascript is through ViewData["Array"].

Question 1: How can I pass javascript values back to C# method?

Question 2: How can I successfully invoke the calculateNumbers() javascript function automatically so that the values are sent back to C#? So for every number it calculates, it would pass the values back to the C# method without invoking it using a button onclick.

C# Method

      public ActionResult Index()
        {
            int[] num_array = { 10, 20, 30, 40, 50, 60, 70 };

            foreach (var numb in num_array)
            {
                ViewData["Array"] = numb;
            }

            return View();
        }

        //values returned from javascript function
        //is saved in db
        public IActionResult SaveResult()
        {
            RandomNumbTable rand = new RandomNumbTable();
            rand.Number = //value from javascript;
            _context.Add(rand);
            _context.SaveChanges();

            return Ok();
        }

.cshtml

<script>
  function calculateNumbers()
        {
            var value = @ViewData["Array"];

            if (value != undefined)
            {
                //random numbers between 1 and whatever value is
                var randomNumbers = Math.floor((Math.random() * value) + 1);

                //I want to grab this value and pass it to the C#
                //SaveResult() method
            }
        }
 </script>

1 Answers1

3

use this for pass values to C# SaveResult Method :

$.ajax({
            url: '/ControllerName/SaveResult',
            type: 'POST',
            data: {rn : randomNumbers}
        }).done(function (t) {
            //--
        });

and :

public IActionResult SaveResult(yourType rn)
        {
            RandomNumbTable rand = new RandomNumbTable();
            rand.Number = rn;
            _context.Add(rand);
            _context.SaveChanges();

            return Ok();
        }

you can invoke calculateNumbers() everywhere like document.ready() based of your requirement.

Afshin Rashidi
  • 343
  • 2
  • 10
  • Thank you so much for the response. It has worked! I was wondering how I could pass values from C# to View using C# models. I've used ViewData, but that isn't something I want to use in my project. I'd appreciate any help! – Jenny From the Block Sep 02 '19 at 18:10
  • please tick answer as correct answer. for passing value from C# to View this link can help you : https://stackoverflow.com/questions/18608452/mvc-4-how-pass-data-correctly-from-controller-to-view – Afshin Rashidi Sep 02 '19 at 18:38