ASP.NET Core ViewData access in javascript - 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();
}

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>

Related

Spring Boot and html not rendering javascript

I am trying to cache some results of a js script. (note this is working for other things like raw string data returned from a service, just not for this. Also note this is the first time I am trying to do it with a script and .js file.
Working:
in html:
<script src="https://www.notmydomain.com/script.js?param1=blah"></script>
not working:
in html:
<script src="/script.js?param1=blah"></script>
in #RestConroller method (from System.out.println's I know its returning the exact same thing as when I call the script directly):
#GetMapping("/script.js")
public String script(Model model, #RequestParam Map<String,String> allRequestParams) {
String parameters = inputParameterBuilder.buildParametersString(allRequestParams);
String js = pagesCacheService.getPage("script.js"+parameters, null, String.class);
if(null == js) {
js = resttemplate.getForObject("https://www.notmydomain.com/script.js" + parameters, String.class);
pagesCacheService.updatePage("script.js"+parameters, js, String.class);
}
return js;
}
Thanks,
Brian
Solved the issue: #GetMapping(value = "/script.js",produces = "text/javascript")

How to display the values coming from springboot controller in javascript

I have a controller which is passing the json object wrapped inside a model.
#RequestMapping("/template")
public String showTemplate(Model model) {
JSONObject obj = new JSONObject();
obj.put("equipmentID", "30584D277D6D4568B17EBB8917D0CB15");
model.addAttribute("template",obj);
return "templates";
}
I would like to use these values in my javascript. I am not able to do that. However, I can see display these values in HTML.
<head>
<script>
function test()
{
var temp = "${template}";
alert(temp); // The values are not displayed here
}
</script>
<body onload="test()">
<span th:text="${template}"> </span> //I can display the values here
<body>
I have also looked into this question How to get spring mvc controller model key value inside javascript? and tried both the options with or without quotes with no success.
I have also tried defining in HTML:
<input type="hidden" id="templates" value='${template}'/>
and using getElementById in my javascript with no success:
var template = document.getElementById("templates");
Using thymeleaf inlining you can use the below:
<script th:inline="javascript">
var message = [[${template}]];
alert(template);
</script>
There are additional ways to access server side variables depending on your use case refer to http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining for more information.

Pass Spring model attribute to JS script

So, I'm having my data parsed to json and then put in the model attributes. Like this:
#RequestMapping("/{id}")
public String getNetworkDetails(Model model, #PathVariable String id) throws JsonProcessingException{
model.addAttribute("poolHashrates", findAndDisplayDataService.getAllPools(Long.valueOf(id)));
model.addAttribute("poolDataJson", findAndDisplayDataService.returnPoolsAsJson(Long.valueOf(id)));
return "networkDetails :: modalContents";
}
Next I'm trying to assign a poolDataJson string to a JS variable in html fragment through:
<script>
var data = eval('('+'${poolDataJson}'+')');
console.log(data);
</script>
What I would like to do with the data, is pass it to external JavaScript file as a data for my pie-chart. But first I'm getting an error on a string assignment:
Uncaught SyntaxError: Unexpected token {
What am I missing?
EDIT
I have also tried assigning json string to hidden input via:
<input type="hidden" id="networkId" th:value="${poolDataJson}"/></td>
And then read it with:
var data = document.getElementById('networkId').innerHTML;
console.log(data);
But again, nothing prints in console. When I put the ${poolDataJson} in it prints properly on a page...
You shouldn't be returning a String as JSON text. Instead, you should return regular Java objects and then evaluate it like this (thymeleaf will automatically convert objects to JSON):
<script th:inline="javascript">
var data = /*[[${poolDataJson}]]*/ {};
console.log(data);
</script>
As for your errors. I would have to guess that your method findAndDisplayDataService.returnPoolsAsJson is returning invalid JSON. Without a real example, it's hard to tell.

cefsharp ExecuteScriptAsync(json) uri too long

I am using cefSharp in my winForm application.
I want to pass a long json from my winform to the html page displayed by the cefSharp.
I tried to write the following:
Private WithEvents m_chromeBrowser As ChromiumWebBrowser
...
CefSharp.Cef.Initialize()
page = New Uri("www...")
m_chromeBrowser = New ChromiumWebBrowser(page.ToString)
Panel.Controls.Add(m_chromeBrowser)
...
Dim json as String = "[{code:1,name:a,val:0},{...}....]"
m_chromeBrowser.ExecuteScriptAsync("functionName('" & json & "');")
But I keep getting the following error:
Request-URI Too Long
Do you have any idea how to pass long json from winform to browser.
Thanks
Well, you would be better off exposing a .Net class to JavaScript by registering an AsyncJSObject, execute the class method from JavaScript and parse the return result.
Something like this:
public class CallbackObjectForJs {
public string getJson() {
return myJsonString;
}
}
... then register the class:
_webBrowser.RegisterAsyncJsObject(
"Browser",
new CallbackObjectForJs(),
BindingOptions.DefaultBinder);
... and finally call the method from Javascript and use a promise to get the result:
Browser.getJson().then((result) => {
var myJsonString = JSON.parse(result);
console.log(myJsonString);
});
You can read more about it here:
https://github.com/cefsharp/CefSharp/wiki/General-Usage#3-how-do-you-expose-a-net-class-to-javascript
Hope it helps!

Embed raw data in HTML to parse in jQuery

I've been living in the desktop world for most of my career, so forgive me for asking such a basic question, but I'm not quite sure where to start looking.
I want to return some raw data along with my HTML, and parse and display the data using jQuery as soon as the HTML is ready. I know roughly what my js code should look like, but I'm not sure how I should embed the raw data in my HTML.
I could use $.getJSON(), but it'd be better if I could have the data right in my HTML.
I think either json or XML would work, but what's the proper way to escape/embed/parse these when they're embedded in HTML?
Thanks in advance.
You can put the JSON data in a hidden div, then decode and use from jQuery.
For example, we'll take:
{"foo":"apple","bar":"orange"}
Escape it and put in a div:
<div id="data">%7B%22foo%22%3A%22apple%22%2C%22bar%22%3A%22orange%22%7D</div>
Then from jQuery, we can use the data:
var data = jQuery.parseJSON(unescape($("#data").html()));
So calling alert(data.foo) will give us apple.
Here's a working example.
Where and when do you want this data?
If you want it in your view, just pass the data to the view
Action/Controller:
public ActionResult MyAction()
{
ViewData["MyData"] = "this is a sample data of type string";
return View();
}
And then, somewhere in your view:
<script>
var data = '<%= ViewData["MyData"] %>';
$(document).ready(){
alert(data);
}
</script>
<h1><%: ViewData["MyData"] %></h1>
Of course, if you're working with a List<string> or `string[]', you would need to format it to proper JavaScript for jQuery to understand it.
<script>
var dataArray = [
<% foreach(string s in (string[])ViewData["MyDataArray"]){ %>
<%= s %>,
<% } %>
];
</script>
It would be getter if you generated the proper JavaScript in the action instead of the view to avoid ugly markup in your view:
public ActionResult MyAction()
{
string[] myArray = new string[]{ "hello", "wolrd" };
ViewData["MyData"] = myArray;
ViewData["JavaScriptArray"] = "[" + myArray.Aggregate((current,next) => string.Format("'{0}','{1}',", current, next).TrimEnd(new char[] { ','})) + "]";
// or you can use your favorite JavaScript serialize
return View();
}
Now you can do the following in your view:
<script>
var dataArray = <%= ViewData["MyJavaScriptArray"] %>;
alert(dataArray[0]); // alerts 'hello'
</script>
Like you said it is probably best to get it via Ajax using $.post or $.get or $(element).load() etc...
But if you must save it in the page it is common to save in a hidden field. Asp.net saves things in hidden fields using binary serialization and Base64 but you can save it as a Json string and then use it in your JS.

Categories

Resources