Send an array using javascript to Spring controller - javascript

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.

Related

on page load call controller method using data from query string

Is it possible to retrieve query string data on page load using javascript?
Let me explain my sample project in steps::
I have a view page showing tabular data. On button press, it retrieves id of the row and calls javascript function.
This javascript function, getDetails(id) has to call another view page, say Application.cshtml.
I have to pass the value of id and a variable message to this view page Application.cshtml.
I am trying to pass this as query string.
Now in this view page Application.cshtml, I have to retrieve the value of id and call contoller method to show the details of the id on page load.
Is it possible to do using javascript?
function getDetails(id)
{
var message = "testing";
var id_ = id;
window.location = "/FirmModels/Application/" + id_;
}
My problem is how can I retrieve the value of id and call controller method on page load using javascript in Application.cshtml?
Your question is a bit unclear but as far as I understood this question you can do this in two ways.
Assuming that you have something like this in your JS file.
window.location = "/Controller/Application?id= " + id_;
In the first method, the View inside your Controller will look like this
public ActionResult Application()
{
string id= Request.QueryString["id"];
//Do your operations here
return View();
}
The second way to do this to pass the id as a mandatory parameter to the view.
public ActionResult Application(string id)
{
return View();
}

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";
}

Send complex object from view to MVC action as none ajax call

I'm working on an ASP.NET MVC web application.
There is a view with a bunch of search filters and there is also a grid in the middle of the page that represents the result of the search.
End-user set value for the search filter and when search button clicked an ajax call returns the values that will rebind the gird.
every row in the grid represents 'ItemId' and 'version' which could be selected by the checkbox.
At the end when the user clicks on "Detail report" we need to redirect the user to another page(view).
I need to pass the selected search filters and the grid selected rows values as an array like this (ItemIds[] and Versions[]) to the "Detail" action.
So, to make the question clear. I need to pass the below values to the action :
search filters
ItemId array
Version array
Unfortunately, I can not pass the parameters to the action. I got null
I can not call the action as ajax call When i use
View (Index.cshtml)
function prepareSelectedInfos() {
var formValues = $('#form').serializeFormToObject();
var gridValues = GetGridSelectedValues();
var dto = {
FormFilters: formValues,
ItemIds : gridValues.ItemIds,
Versions : gridValues.Versions
}
return dto;
}
$('#lnkDetailReport').click(function () {
var gridValues = GetGridSelectedValues();
var url = '/Report/Controller/Detail/';
var dto = prepareSelectedInfos();
window.open(url + dto, '_blank');
});
Controller
public ActionResult Detail(ModelVersionStatisticalDetailDto data)
{
//create a ViewModel according to the incoming data
var viewModel = ;
return View(viewModel);
}
Model
public class ModelVersionStatisticalDetailDto
{
public ModelVersionStatisticalReportDto FormFilters { get; set; }
public int [] ItemIds { get; set; }
public string[] Versions { get; set; }
}
I need to have the view prepared values in the Detail action
To the best of my recollection, it is not possible to perform a redirect after having post a complex object in ajax call (with the same posted parameters).
In order to perform your desired operation, you can choose a solution from below.
Use query strings in your Detail action and perform a simple post action instead of ajax call
Try to replace the response of Detail action with Partial View
If you are seeking a client side solution, you can assist from localStorage object (a tricky solution). You can store the required data in a localStorage object and pass the key to the controller. In the target page, use the key in order to fetch the data stored in storage. Do not forget to clear it after the process. https://blog.logrocket.com/the-complete-guide-to-using-localstorage-in-javascript-apps-ba44edb53a36/

error in MVC, when I pass as parameter '&' fails

I have an error in MVC, when I pass as parameter '&' fails to come the following. How will I show in this example?
public IActionResult Create(int? idTrabalhador, [FromQuery]string GridState{}
view
var lnk = "#Url.Action("Create" , new { idTrabalhador = "{#KeyTrabalhador}", GridState = "{#GRID_STATE}" })";
lnk = lnk.replace(encodeURIComponent("{#KeyTrabalhador}"), 0);
lnk = lnk.replace(encodeURIComponent("{#GRID_STATE}"), JSON.stringify(state));
http://localhost:58185/TrabalhadorPincodes/Create?idTrabalhador=0&GridState={"filter":{"NomeTrabalhador":"nuno","Estado":"0"},"sorter":[],"currentPage":0}
model =>
GridState = "{\"filter\":{\"NomeTrabalhador\":\"nuno\",\"Estado\":\"0\"},\"sorter\":[],\"currentPage\":0}"
Perfect!!!
BUT
http://localhost:58185/TrabalhadorPincodes/Create?idTrabalhador=0&GridState={"filter":{"NomeTrabalhador":"&","Estado":"0"},"sorter":[],"currentPage":0}
model =>
GridState = "{\"filter\":{\"NomeTrabalhador\":\""
need help!!!
The browser is interpreting the & as part of the url as you are sending the http request via the GET method.
One method to handle this is to urlEncode your parameters using Server.UrlEncode
This also means you will need to decode the parameters within your controller.
The other solution is to post the values so that they are not part of the url but you will need to decide whether this is appropriate.
because the 'encodeURIComponent' only works in plain text, what I'm doing is creating a compound object soon does not work. I have to use the 'encodeURIComponent' as soon as the object is constructed not after it is built
filter.NomeTrabalhador = encodeURIComponent($('#NomeTrabalhador').val());

Avoid displaying returned data from Spring #ResponseBody on browser

Okay, curerntly I am displaying some data on a html page. I have used jquery ajax call which get the data from the specific url on spring MVC application and return data and then use javascript to display data in the table.
#RequestMapping(value = "/students", method = RequestMethod.GET)
#ResponseBody
#JsonView(Views.PublicView.class)
public ArrayList<Student> getAdminsList(HttpSession session) {
//return data
}
Now, my question is, I get data as I required via ajax, but I do get data displayed in the browser if I just go through url: www.example.com/students - will display JSON data.
Is there anyway to avoid display this data not in browser but only in ajax call?
Anyway, I just found the answer for this after lots of googling and I thought sharing it would be good thing. So, basically what is the logic for this restriction is that, whenever a call is made from ajax a special header named X-Requested-With with a value of XMLHttpRequest is attached to the request. the only thing I have to do is check this parameter on my controller.
#RequestMapping(value = "/accounts", method = RequestMethod.GET)
#JsonView(View.Accounts.class)
public List<Account> getAccounts() throws JsonProcessingException {
if(!"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
log.info("Request is from browser.");
return null;
}
List<Account> accounts = accountService.findAccounts();
return accounts;
}
you can read the full article on this blog. http://www.gmarwaha.com/blog/2009/06/27/is-it-an-ajax-request-or-a-normal-request/
Maybe feels like being a problem[#JsonView(Views.PublicView.class)]. You check PublicView.class
Read to description. link : enter link description here
#RequestMapping(value = "/accounts", method = RequestMethod.GET)
#JsonView(View.Accounts.class)
public List<Account> getAccounts() throws JsonProcessingException {
List<Account> accounts = accountService.findAccounts();
return accounts;
}

Categories