6

I am sending a filepath ( string) from controller to html page through ViewData and I want to access that string in my javascript, consume it, run some algo in javascript and then use results to consume them and make some graphs on the same html page.

HTML

</head>
<body>
    <div id="mychart"></div>
    <script>
        var path=@ViewData["path"];
        //some javascript logic with the string path of the file.
        //using results for output chart of id 'mychart'
    </script>
</body>
</html>

Controller Action Code:

        public IActionResult CellResult(string outputpath)
        {
            ViewData["path"] = outputPath;
            return View();
        }

1 Answer 1

10

Since it is a string value, you need to wrap it in either single quotes or double quotes.

var path='@ViewData["path"]';
alert(path);

EDIT : As per the comment

How can I send a list of string from controller to html page and use it in javascript? instead of string i wanna send a list of string

If you want to send a list of string, it is the same, but since it is a complex type now, you need to use the json serializer to convert this object to a string.

So in your server

var list = new List<string> {"Hi", "Hello"};
ViewBag.MyList = list;

and in the view

<script>
    var list = @Html.Raw(JsonConvert.SerializeObject(ViewBag.MyList));
    console.log(list);
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

can u also please tell me how can I send a list of string from controller to html page and use it in javascript? instead of string i wanna send a list of string
How do you transform the serializefd object to a object in javascript?

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.