Jenny From the Block
Jenny From the Block

Reputation: 171

How to pass Javascript values located in Views to C# method

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>

Upvotes: 1

Views: 726

Answers (1)

Afshin Rashidi
Afshin Rashidi

Reputation: 353

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.

Upvotes: 3

Related Questions