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}]];
Related
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;
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";
}
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';
I'm working on a jsp page and I need a Javascript variable as parameter inside a java function e.g.:
<script>
function example(string){
<% javaFunction(string); %>
}
</script>
how can I pass the javascript String variable to the java fucntion?
DONT USE SCRIPTLETS IN JSP!.
You must understand jsp (views) code is executed in client side, java one is at server (host) one.
In order to get variables from the host side, you have plenty vays, but for small things best option is to make an ajax call:
$.get( "javaFunction",
{ variable: "VALUE" }
).done(function( data ) {
alert("Java function returned " + msg);
});
In java you need to map the url:
#RequestMapping(value = "/javaFunction", method = RequestMethod.POST)
public
#ResponseBody
String javaMethod(#RequestParam("variable") String variable) {
if (variable.equals("VALUE") {
return "Correct call!";
} else {
return "Mistake!";
}
}
I´m making a call using javascript and I would like to send an array:
var selected = [];
selected=getAllEnginesIdsSelected();
console.log("selected: "+selected);
$.getJSON('/call/' + selected,
function(myList) {
Console.log retrieves selected: 2,5
In MVC Controller I have
#RequestMapping(method = RequestMethod.GET, value = "/call/{selected}")
public List<List<myList>> myCall(#RequestParam(value="selected[]") String[] selected){
I gives an error. I don´t want to use AJAX. This is posible to send?
EDIT
The funcion that I use in Javascript to retrieve array is:
function getAllEnginesIdsSelected() {
var selected = [];
$("input:checkbox[id^='engine_']:checked").each(function(){
var ele=$(this)[0].id;
});
return selected;
}
I guess you should use #PathVariable instead of #RequestParam in your controller.
You can get all the request parameters you send to spring controller by using:
#RequestParam Map<String,String> allRequestParams
You need to assign a name to each parameter to retrieve them later:
?a=1&b=2&c=3
Another way is to serialize your data and send a POST request to the controller.