How to get value from spring controller class in javascript? - javascript

I have a controller class in spring. I am passing values such as a simple string or a hashmap. I know how to get values in thymeleaf. I want to get values on my html page in pure javascript, no thymeleaf. My controller class :
String s="RUSSIA";
#RequestMapping(value = "/", method = RequestMethod.GET)
public String Country( Model model) {
model.addAttribute("country", s);
return "index";
}
Now I want to get this string in javascript variable. I am using HTML not JSP.

You could do something like this:
<script th:inline="javascript">
/*<![CDATA[*/
var country = [[${country}]];
console.log(country);
/*]]>*/
</script>
If you want to run your html offline you can do this, and the JS variable will be always the fixed value of Russia
var country = /*[[${country}]]*/ 'Russia';

Related

How to pass entire ViewModel into External Javascript file in .net core mvc 3.1?

I would like to pass my entire ViewModel from a .cshtml file into an External Javascript that is included in the same cshtml file.
I have tried different solutions but none of them work. I first started with reguarl js variable in cshtml file and passed it into the external js file.
E.g for the below code when I click on the below button I get, Uncaught ReferenceError: myValue is not defined
**- in test.cshtml file:**
<button onclick="testAlert()"></button>
<script language="text/javascript">
var myValue = "myValue test";
</script>
<script src="~/js/test.js"></script>
**in test.js:**
/**
* This is a test alert function in external js.
* */
function testAlert() {
console.log(myValue);
}
The above is just a test for regular variables which if when it works, then I would like the below object in the external javascript like below.
***in test.cshtml:***
var customer = #Html.Raw(JsonConvert.SerializeObject(Model.CustomerDetails));
***Then in test.js***
function testAlert() {
console.log(customer.Names.FirstName);
}
As far as I know, if you want to pass the model to JS scripts, I suggest you could use #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(object model)) to convert the model to a json string as #Seabizkit suggests. Then you could convert this json to model in the js and read its property.
More details, you could refer to below codes:
Model class:
public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public string SemesterNumber { get; set; }
}
In your view set a button like below:
<input type="button" onclick="testAlert()" value="test" />
Then add a script at cshtml like below:
#section scripts{
<script>
// Notice: we should add '' between the html.raw to set it as a json string.
var customer = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))';
</script>
}
Then in the another js file add below codes:
Since my model is just a simple model like this to test, if you want to use my codes, you should modify it.
function testAlert() {
console.log(customer);
var ce = JSON.parse(customer);
alert(ce.SemesterNumber);
}
Result:
i think.... you lookng for
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
so in your case something like
function testAlert() {
var customer = #Html.Raw(JsonConvert.SerializeObject(Model.CustomerDetails));
var customerJson = JSON.parse(customer);
console.log(customerJson.Names.FirstName);
}
I got my own answer but was not fully satisfied with it yet, so didn't post until today.
Need more refinement though.
test.cshtml:
#using Newtonsoft.Json;
<script type="text/cshtml">
viewmodel = #Html.Raw(JsonConvert.SerializeObject(Model));
</script>
test.js:
at the top:
var viewmodel;
Only by doing this does it work correctly. Most similar to #brando Zang's answer except for the extra initializing part. Still not sure why it works without var or let in the main cshtml page.
Also, intellisense is not working yet on my external js file test.js.
But thanks a ton to Brando Zang and Sea Bizkut for taking the time to help me out.
Some findings which will be useful for other people:
In default .net core mvc 3.1 , the default json is automatically converting viewmodel values to camelcase from pascal case, so using newtonsoft instead keeps default functionality and naming conventions.
Can do it for default JSon parser itself in startup itself but it is a hassle, so using Newtonsoft instead.
Also for enum values, it takes the value and not the string by default. so in the model. e.g in js object for CustomerType you will get 0,1,2 instead of Standard, Premium or VIP. so to fix it,
(VB syntax below for enum - not able to show code indented properly in SO)
Public Enum CustomerType
Standard = 0
Premium = 1
VIP = 2
End Enum
TestModel.cs:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
[JsonConverter(typeof(StringEnumConverter))]
public CustomerType CustomerType;

How to handle variable from Spring controller using javascript?

Guys i have problem to get data from variable after execute rest in my controller. Here is sample to show my problem.
Controller
#RequestMapping(path = "/editSchema/{id}")
public String editSchemaById(Model model, #PathVariable("id") Integer id)
{
model.addAttribute("message", "why this isn't working...");
return "redirect:/drawdiagram";
}
JavaScript drawdiagram.html
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[[${message}]]*/ 'default';
/*]]>*/
</script>
Result
Anyony can tell me why i have null there?
I really don't know what is going on :(
Maybe this is bad way? I have chosen thymeleaf but maybe there is some other way?
All i need to do is:
1. Click button.
2. Execute some backend code and get data to variable in controller.
3. Redirect to other page.
4. Execute some JavaScript code which is based on that variable.
.
Sources:
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart
Setting up a JavaScript variable from Spring model by using Thymeleaf
you are redirecting to another controller drawdiagram, the values in model object won't be available in other controller. So here you need to set the value first using either RedirectAttributes#addFlashAttribute or RedirectAttributes#addAttribute, and then get the value in the other controller -using #ModelAttribute("message").
#RequestMapping(path = "/editSchema/{id}")
public String editSchemaById(Model model, #PathVariable("id") Integer id, RedirectAttributes redirectAttributes)
{
redirectAttributes.addFlashAttribute("message", "why this isn't working...");
return "redirect:/drawdiagram";
}
#RequestMapping(value = "drawdiagram", method = RequestMethod.GET)
public String OtherController(#ModelAttribute("message") String message, Model model) {
model.addAttribute("message", message);
return "drawdiagram";
}

Retrieve ModelMap value from Spring MVC controller to jquery in html

I am doing project in Spring 4.0.2. In Spring MVC controller I have used ModelMap attributes and I want to retrieve the same in jquery in html file.
My Servlet code
#RequestMapping(value = "/search", method = RequestMethod.GET)
public String search(ModelMap model,#ModelAttribute TravelSearchDTO travelSearchForm, HttpServletRequest request) {
Integer maxSeatSelection = dto.getMaxSeats();
model.addAttribute("maxSeatNo",maxSeatSelection);
String returnText = "static/html/search";
return returnText;
}
My jquery code in search.html
<script type="text/javascript">
var ss = '${maxSeatNo}';
alert(ss);
</script>
No alert for ss value appeared. Also I am in great doubt that whether I need to use the variable in script declaration or in document.ready function. Please clarify above doubts to access the Modelmap value in html.
Try using var ss = "${maxSeatNo}";
This should work.
Try using:
var ss = [[${maxSeatNo}]];

Can I define a javascript variable to a grails object?

Can I assign a javascript variable to a grails object like this?
var newReport = ${report};
report is a grails domain object, which is passed back from controller to the gsp file.
Currently this doesn't work in my page.
Assuming that report is a Grails domain class, you will have to 'translate' this to a valid javascript format. One way is to set this as JSON. Something like:
In the controller
def reportJson = report as JSON
In the gsp
<script type='text/javascript'>
var newReport = $.parseJSON("${reportJson}");
</script>
The parseJSON takes the json string and return a javascript object.
Just render domain object as JSON to gsp, where some javascript code get the json by eval() function. For instance:
domain class - Band:
String bandName //some property
...
controller:
def bands = Band.list()
render(template:"result", model:[bands:bands as JSON]
_result.gsp:
<script>
var bandList = eval(${bands});
for(i=0; i<bandList.length; i++){
var name = bandList[i].bandName;
....
}
....
</script>

Pass a string from the controller to a partial view as javascript function parameter

I have a controller
public ActionResult controller(){
Viewclass view = new Viewclass();
...
return PartialView("Tab", view);
}
In which the view class is something like, the string A and B is my compiled JSON string.
public class ViewClass
{public string A {get;set;}
public string B {get;set;}
}
In the Partial view, I want to do
<script type="text/javascript">
RunMap( #Model.A, #Model.B);
</script>
The problem is the " is parsed as &quot, like {&quotCity&quot:} into the function. How can I fix this?
Use #Html.Raw to treat the string as raw HTML (e.g MVC will not encode it)
<script type="text/javascript">
RunMap(#Html.Raw(Model.A), #Html.Raw(Model.B));
</script>
Of course, you need to make sure that the input (e.g the data) it handled carefully.
This should work: RunMap( "#Model.A", "#Model.B");
If you want to pass them as JSON objects, then take out the quotes.

Categories