1

So I am trying to pass the data (int-Array) from my Model...

namespace MvcApplication2.Models {
    public class Sudoku {
        public int[] numbers { get; set; }
    }
}

..., initialized with indices by the Controller ...

namespace MvcApplication2.Controllers
{
    public class SudokuController : Controller
    {
        //
        // GET: /Sudoku/

        [HttpGet]
        public ActionResult Index()
        {
            Sudoku sudoku = new Sudoku();

            int[] numbers = new int[81];
            for (var i = 0; i < 81; i++) {
                numbers[i] = i;
            }
            sudoku.numbers = numbers;

            return View(sudoku);
        }
    }
}

... through the View ...

@model MvcApplication2.Models.Sudoku
@{
    ViewBag.Title = "Sudoku";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Sudoku</h1>

<div class="sudoku"></div>

@section scripts {
    <script id="script1" src="~/Scripts/render_sudoku.js" type="text/javascript" data-numbers=@Model.numbers></script>
}

... into my JavaScript file, where I just want to use it as an array.

However, when I try

console.log($('#script1').data("numbers"));,

I only get

System.Int32[]

as an answer, which seems to be a String only describing the format.

Is it possible to work with the actual Array in the JavaScript file?

I'm new to MVC and can't quite get the grasp of it.

Murph
  • 76
  • 1
  • 7
  • 1
    What do you get with this instead? : `console.log($('#script1').data("numbers")[0]);` – Crowcoder Aug 22 '18 at 12:00
  • 1
    Try `console.log($('#script1').data("numbers").join());` (look [JavaScript join()](https://www.w3schools.com/jsref/jsref_join.asp)) – Rafalon Aug 22 '18 at 12:00
  • 1
    @Crowcoder This returns `S`, so just the first letter of the String. – Murph Aug 22 '18 at 12:02
  • 1
    @Rafalon That gives me `Uncaught TypeError: $(...).data(...).join is not a function`, I guess because it isn't an array? – Murph Aug 22 '18 at 12:04
  • 1
    becuase @Model.numbers is List of int objects so it display its string value you cant access like this – Lalji Dhameliya Aug 22 '18 at 12:11
  • Lalji is right, try using `data-numbers='@String.Join(",",Model.numbers")'` then split it in your javascript to have it as an array ([C# String.Join](https://msdn.microsoft.com/fr-fr/library/dd988350(v=vs.110).aspx)) – Rafalon Aug 22 '18 at 12:14

3 Answers3

2

Problem: @Model.numbers is List of int objects so it display its string value you cant access like this, because it convert into object string.

Solution: Above answer is right but if you want to access direct JavaScript variable as array like below, You can set int string array to java-script variable like below.

   <script>
        var sudokuNumbers = [@string.Join(",", Model.numbers)]
   </script>

Not require to split string into array in JavaScript.

now you can access sudokuNumbers, this variable is javascript array. and you can access its value. i hope it helps you.

Lalji Dhameliya
  • 1,729
  • 1
  • 17
  • 26
1

I'd suggest you pass the list of numbers as a variable inside the scripts-section, instead of setting it as a data-attribute of the tag inside it. You can then use the variable in you script.

In your view:

@section scripts {
    <script>
        var mynumbers = "@string.Join(",", Model.numbers)";
    </script>
    <script id="script1" src="~/Scripts/render_sudoku.js" type="text/javascript"></script>
}

In your script:

var numbers = mynumbers.split(",");
for (var i in numbers)
{
    var number = numbers[i];
    // DO WHATEVER
}

Edit: You need to put the declaration of the Javascript variable inside quotes, or otherwise you will get an ESLint parsing error.

ZiNNED
  • 2,620
  • 20
  • 31
  • Couldn't it work this way without joining and splitting? `var mynumbers = @Model.numbers`? – Rafalon Aug 22 '18 at 12:18
  • Hmm.. Not sure, it could work, haven't tried it. But that would indeed save the two extra operations. Edit: That would probably not work. ESLint will throw a parsing error on the line declaring the variable, expecting a string. – ZiNNED Aug 22 '18 at 12:19
  • @Rafalon you can directly set your javascript variable as array var sudokuNumbers = [@string.Join(",", Model.numbers);] so not required to split – Lalji Dhameliya Aug 22 '18 at 12:37
  • Thanks, that solved it! I didn't know I could declare a global variable in the scripts-section of the View and use it in my external script. – Murph Aug 22 '18 at 12:45
0

The best way to do it IMO is through a serializer from the Framework that can process just about anything, not only arrays. That way you never have to worry about details of the formatting, escape sequences, special cases etc.

In the View:

@using System.Web.Script.Serialization
@{
    var serializer = new JavaScriptSerializer();
}
<script>
    var numbers = @Html.Raw(serializer.Serialize(Model.numbers));
</script>
Peter B
  • 22,460
  • 5
  • 32
  • 69