1

I have a list in Razor Page which i want to use in java script.I'm using viewdata to send data to view VIewbag is working for some reason in razor page. I'm using .net core 2.2

Things i already tried.

View

Things i already tried:

  1. var [email protected]
  2. var stringArray = @Html.Raw (Json.Serialize(ViewData["Quest"]));` viewdata[Quest] contains list
  3. string jsonn = JsonConvert.SerializeObject(quelist);` and then send jsoon to view.
  4. using custom class object and create create json object using Newtonsoft.Json and send to view

If you proposing ajex solution explain it a little as i dont know much about it or share a link for explanation

Razor page .cs file Commented the things that didn't

public async Task OnGetAsync()
{           
  ViewData["opt1"] = o1list;
  ViewData["quest"] = quelist;
  //   string jsonn = JsonConvert.SerializeObject(quelist);
  //   ViewData["Jon"] = jsonn;
  QuestionBank = await _context.QuestionBank
                .Include(q => q.QuestionLevel)
                .Include(q => q.QuestionStyle)
                .Include(q => q.Teacher)
                .Include(q => q.Topic).ToListAsync();
   Answer = await _context.Answer.ToListAsync();
   QSID = await _context.QSID.ToListAsync();

View

    @{var name = (List<String>)ViewData["Quest"]; }
    <script>
    /*function test() {
    var array = @Html.Raw(Json.Serialize(ViewData["Jon"]));
    for(var i = 0; i < array.length; i++) {
        alert(array[i]);
        console.log(array[i]);
    }
    }
    test();
    */</script>
</head>
<body>
    @{
          Model.run();
          var name = (List<String>)ViewData["Quest"];
          var nam = (List<String>)ViewData["opt1"];
          int j = 0;
          for (int i = 0; i <= 4; i++)
          {
              var a = name[i];
              <p > @a </p>

              <form action="">
                  <input type="radio" name="s" value="">@nam[j]<br>
                  @{j = j + 1; }
                  <input type="radio" name="s" value="">@nam[j]<br>
                  @{j = j + 1; }
                  <input type="radio" name="s" value="">@nam[j]<br>
                  @{j = j + 1; }
                  <input type="radio" name="s" value="">@nam[j]
                  @{j = j + 1; }
              </form>
          }
    }

I expect to get a array containing my list or in json format

2
  • You store the data with ViewData["jon"] in your controller, but you try to access it with ViewData[Jon"] in your view. The key should have the same case for it to work. Commented Apr 21, 2019 at 8:00
  • that is not the problem i corrected it same result.. Commented Apr 23, 2019 at 10:18

2 Answers 2

1

This is how I do it in a project I created:

<script>
    var saleTypesById = @Html.Raw(JsonConvert.SerializeObject(Model.TypesById));
</script>

Where Model.TypesById is a Dictionary<long,SaleType>.

To use from javascript I call:

var selectedSaleType = saleTypesById[selectedId];

Then I can just call properties on it like selectedSaleType.Comission

This code requires @using Newtonsoft.Json; directive and a reference to the corresponding nugget package.

Sign up to request clarification or add additional context in comments.

Comments

0

I follow the above example but with an extra step:

    <script type="text/javascript">

                window.onload = function () {

                    try {
                        var movsArray = '@Html.Raw(JsonConvert.SerializeObject(Model))';

                        var opt = JSON.parse(movsArray);//Extra step

                        if (opt.length > 0) {
                        //You can use opt as array of objects

                        }

                    } catch (Error) {
                        console.log("Error");
                    }
                };
    </script>

or maybe you can use a loop instead of if

        <script type="text/javascript">

                    window.onload = function () {

                        try {
                            var movsArray = '@Html.Raw(JsonConvert.SerializeObject(Model))';

                            var opt = JSON.parse(movsArray); //Extra step
                            for(var i = 0;i<opt.length;i++){
                            //you can use opt[i] as object, example opt[i].id
                            }

                        } catch (Error) {
                            console.log("Error");
                        }
                    };
        </script>

Where Model is List<Mov_Tipo>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.