0

need help here. May I know if I did anything wrong. Apparently, it's not working.

Controller:

[HttpGet]
public IActionResult Index()
{

    var data = new List<String>();
    data.Add("No");
    data.Add("Yes");
    data.Add("543");


    ViewBag.Name= data;
    return View(model);
}

View

        function Validation(IsValid) {
         var test = '@ViewBag.Name';
         var a = "Yes"
         for (var z = 0; z < test.length; z++)
         {
           if (a == test[z]) {
           ...then..
           }
         }
        }

How do I accessed the "No", "Yes", and "543" inside the JavaScript?

Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
Sarah
  • 329
  • 5
  • 21
  • `var test = @Html.Raw(Json.Encode(ViewBag.Name))` to convert your model to a javascript array. –  Jan 23 '18 at 07:25
  • Suggest you also learn some basics of debugging your scripts using your browser tools. Even a basic `console.log(test);` would make it clear where the issue is. –  Jan 23 '18 at 07:59
  • @StephenMuecke Thanks for the update. May I know how to solve the problem of "Cannot resolve symbol Encode" ? – Sarah Jan 23 '18 at 08:19
  • Just noticed you have `IActionResult` which means you should have tagged this [tag:asp.net-core-mvc]. In which case refer [this answer](https://stackoverflow.com/questions/30301930/where-are-json-encode-or-json-decode-methods-in-mvc-6) for the equivalent of `Json.Encode` –  Jan 23 '18 at 08:23

1 Answers1

0

You can try this

    function Validation(IsValid) {
        var test = '@(string.Join(",",((List<string>)ViewBag.Name)))'.split(",");
        var a = "Yes"
        for (var z = 0; z < test.length; z++)
        {
            if (a == test[z]) {
                //...then..
            }
        }
    }
Nitesh Kumar
  • 1,774
  • 4
  • 19
  • 26