Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core ViewData access in javascript

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();
        }
like image 814
Muhammad Touseef Avatar asked Dec 30 '16 14:12

Muhammad Touseef


People also ask

How do I pass a ViewBag in JavaScript?

The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed inside JavaScript function using Razor syntax in ASP.Net MVC Razor.

Can we use ViewData in jQuery?

ViewData is created on Server Side of the Web application and hence it is not possible to directly set it on Client Side using JavaScript or jQuery.

Which syntax is used to store a string value into ViewData?

ViewData is a derivative of the ViewDataDictionary class, so you can access by the familiar "key/value" syntax, in other words it is a dictionary of objects that are accessible using strings as keys.

What is ViewData in asp net core?

In MVC, when we want to transfer the data from the controller to view, we use ViewData. It is a dictionary type that stores the data internally. ViewData contains key-value pairs which means each key must be a string in a dictionary. The only limitation of ViewData is, it can transfer data from controller to view.


1 Answers

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>
like image 193
Shyju Avatar answered Sep 19 '22 12:09

Shyju