how to read the controller ModelAndView setObject in Javascript in Spring Boot? - javascript

I have a controller which has set some values and I am returning the ModelAndView Object. Now I am able to access this object in the Thyme-leaf but unable to access in the javascript file. Any suggestions?
I tried using
[CDATA[/ ... var username = /[[${session.user.name}]]/ 'Sebastian'; ... /]]>
It worked perfectly when I am writing the script in thymeleaf page itself but it doesn't work when I am creating the separate JavaScript file and writing the same code

Related

Access RESX file from external javascript file [duplicate]

How would one get resx resource strings into javascript code stored in a .js file?
If your javascript is in a script block in the markup, you can use this syntax:
<%$Resources:Resource, FieldName %>
and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed.
I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active.
One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser?
Or does anyone have any other suggestions?
Here is my solution for now. I am sure I will need to make it more versatile in the future... but so far this is good.
using System.Collections;
using System.Linq;
using System.Resources;
using System.Web.Mvc;
using System.Web.Script.Serialization;
public class ResourcesController : Controller
{
private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
public ActionResult GetResourcesJavaScript(string resxFileName)
{
var resourceDictionary = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/" + resxFileName + ".resx"))
.Cast<DictionaryEntry>()
.ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
var json = Serializer.Serialize(resourceDictionary);
var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json);
return JavaScript(javaScript);
}
}
// In the RegisterRoutes method in Global.asax:
routes.MapRoute("Resources", "resources/{resxFileName}.js", new { controller = "Resources", action = "GetResourcesJavaScript" });
So I can do
<script src="/resources/Foo.js"></script>
and then my scripts can reference e.g. window.Resources.Foo.Bar and get a string.
There's no native support for this.
I built a JavaScriptResourceHandler a while ago that can serve Serverside resources into the client page via objects where each property on the object represents a localization resource id and its value. You can check this out and download it from this blog post:
http://www.west-wind.com/Weblog/posts/698097.aspx
I've been using this extensively in a number of apps and it works well. The main win on this is that you can localize your resources in one place (Resx or in my case a custom ResourceProvider using a database) rather than having to have multiple localization schemes.
whereas "Common" is the name of the resource file and Msg1 is the fieldname. This also works for culture changes.
Partial Javascript...:
messages:
{
<%=txtRequiredField.UniqueID %>:{
required: "<%=Resources.Common.Msg1 %>",
maxlength: "Only 50 character allowed in required field."
}
}
In a nutshell, make ASP.NET serve javascript rather than HTML for a specific page. Cleanest if done as a custom IHttpHandler, but in a pinch a page will do, just remember to:
1) Clear out all the ASP.NET stuff and make it look like a JS file.
2) Set the content-type to "text/javascript" in the codebehind.
Once you have a script like this setup, you can then create a client-side copy of your resources that other client-side scripts can reference from your app.
If you have your resources in a separate assembly you can use the ResourceSet instead of the filename. Building on #Domenics great answer:
public class ResourcesController : Controller
{
private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
public ActionResult GetResourcesJavaScript()
{
// This avoids the file path dependency.
ResourceSet resourceSet = MyResource.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
// Create dictionary.
var resourceDictionary = resourceSet
.Cast<DictionaryEntry>()
.ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
var json = Serializer.Serialize(resourceDictionary);
var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.resources = {1};", json);
return JavaScript(javaScript);
}
}
The downside is that this will not enable more than one resource-file per action. In that way #Domenics answer is more generic and reusable.
You may also consider using OutputCache, since the resource won't change a lot between requests.
[OutputCache(Duration = 3600, Location = OutputCacheLocation.ServerAndClient)]
public ActionResult GetResourcesJavaScript()
{
// Logic here...
}
http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs
I usually pass the resource string as a parameter to whatever javascript function I'm calling, that way I can continue to use the expression syntax in the HTML.
I the brown field application I'm working on we have an xslt that transforms the resx file into a javascript file as part of the build process. This works well since this is a web application. I'm not sure if the original question is a web application.
use a hidden field to hold the resource string value and then access the field value in javascript
for example :
" />
var todayString= $("input[name=TodayString][type=hidden]").val();
Add the function in the BasePage class:
protected string GetLanguageText(string _key)
{
System.Resources.ResourceManager _resourceTemp = new System.Resources.ResourceManager("Resources.Language", System.Reflection.Assembly.Load("App_GlobalResources"));
return _resourceTemp.GetString(_key);
}
Javascript:
var _resurceValue = "<%=GetLanguageText("UserName")%>";
or direct use:
var _resurceValue = "<%= Resources.Language.UserName %>";
Note:
The Language is my resouce name. Exam: Language.resx and Language.en-US.resx

Convert in JavaScript C# code that reads from web.config

in the web.config file of my ASP.NET MVC application I have some constant string values.
sommething like this:
<add key="filters" value="AA;BB;CC;DD" />
In a C# file I create a List in this way:
List<string> filters = new List<string>(ConfigurationManager.AppSettings["filter"].Split(new char[] { ';' }));
Now I have to put this code in a JavaScript file
and create as many string variables as strings are present in this List.
For example, in this case I should obtain:
filterAA
filterBB
filterCC
filterDD
How can I accomplish this task?
Thank you in advance.
Luis
You can add List to a view model in a controller, then you sent the data to View via ViewModel. Add this code inside of View
#model ViewModel
... your html code
<script>
var filters = #Html.Raw(Json.Serialize(#Model.Filters));
</script>

How to access array of python in JavaScript from Views in Django?

I am writing this array in Views in Django:
address=["Main Address"]
and passing in dic. and accessing in Java Script in HTML page:
address={{context.lat_long.address}}
addMarker(address,{lat: property_lat, lng: property_long}, "red");
But it is not working at all
You need to understand how Django templating works.
The template data (Jinja) are generated in the backend, before sending the page.
The JS code is runing in the front.
You can do it in the following way,
In django views,
address=["Main Address"]
return render_template('page.html', address=address)
In the page.html and the attached javascript, you can access the variable as,
var a = {{ address }};

How to use information sended by the controller in a JavaScript file using Spring Boot?

I'm using Spring Boot with the Thymeleaf template engine. I have a HTML called clients.html file in the templates folder and a JavaScript file called functions.js in the static folder. I want to send from the controller to the JavaScript file a List.
I have tried using this syntax in the JavaScript file:
let listaArticulos = /*[[${numeroArticulos}]]*/ [];
But I don't recive anything. I have tried using the script tag in the HTML and it worked, but I want to have the JS code in a separate file and not in a script tag with all my html code.
The controller where I send the information to the JS looks like this:
#GetMapping("/articulos")
public ModelAndView showHielo(#RequestParam(name = "numcli", required = false) String numcli){
ModelAndView mav = new ModelAndView(ViewConstant.ARTICULOS);
mav.addObject("numeroArticulos", searchMovimNumarts(" 133"));
return mav;
}
Where the controller send the searchMovimNumarts() method with the name of "numeroArticulos" the one returns a List.
And the JS file where I want to recive the "numeroArticulos" object looks like this:
/*This variable stores data sended by the controller*/
let listaArticulos = /*[[${numeroArticulos}]]*/ [];
console.log(listaArticulos);
I want to console log the content of the List using a JS file and no the html
tag. How can I solve this?
Thymeleaf template engine parses only the template file(html files). So you have to include those variables defined in the controller into the embedded js code. However You don't have to put your entire js code in your html. Have only that part of code that refer to those variables in script tag.
<script>
let listaArticulos = /*[[${numeroArticulos}]]*/ [];
</script>
and refer them in your external js after this
<script src="/js/externalscript.js"></script>

Accessing MVC server side variable in Javascript

I'm moving one of our web applications from Drupal to an ASP.net MVC Web Application.
One of the Drupal functions gets some data from a web service and converts it to a JS Array, as follows:
foreach ($xml_result->JobList->JobDetail as $job_detail) {
// dsm((array)$job_detail);
$open_job_details[] = array("east"=>(string)$job_detail->Easting,"north"=>(string)$job_detail->Northing, "duedate"=>(string)$job_detail->openDate);
}
//dsm($open_job_details);
$open_jobs_data = json_encode($open_job_details);
drupal_add_js(array('open_jobs' => array('open_newjobs' => $open_jobs_data)), 'setting');
In the Javascript file, it is accessed using;
var openJobsData = JSON.parse(Drupal.settings.open_jobs.open_newjobs);
Is there a simple way to access a server side variable in the JS file in .NET? I can call the web service and get the relevant data from the XML file but not sure how to access it in the JS file.
Thanks
You can use Strongly Typed view to create cshtml page
if you want to access JSON object
View1.cshtml
#model mvcApplication1.Models.model1
#{
var serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue;
var jsonModel = serializer.Serialize(Model);
}
var JsonData = #Html.Raw(jsonModel); // declare a javascript variable and use it
if you want to access server variable at cshtml page
just use # to access server-side variables
after getting the value you can use javascript variable in another js file
Declare your javascript variable outside
$(document).ready(function()
{}
or before using the variable
you can use that variable in Javascript file.

Categories

Resources