Access to Java model List from Javascript/JQuery dynamically - javascript

I have a model as List<Collaborateur> coming from my Controller Action to my JSP. And I have the following function in JQuery/Javascript:
function showCollaborateurEmail(index) {
alert("${collaborateurs[1].email}"); // Works
alert("${collaborateurs[2].email}"); // Works
//....
alert("${collaborateurs[index].email}"); // Not working
}
So I want to show the email of my Collaborateur model dynamically by calling the function showCollaborateurEmail(index).
Thank you for your help!

The problem that you face is the exchange of data between code on server side and code on client side. There are multiple ways to achieve your goal. You can...
store the list-elements in a hidden form-field (escaping of delimiter might be a challenge) or
generate javascript - code on server side in JSP that creates a javascript array with the list-elements or
use ajax.
1 and 2 are rather ad hoc - solutions for a small problem. 3 is rather a bigger solution (depending on your technical environment) which additionally provides the possibility to avoid page reloads.

Two approaches to explore:
1) generate a javascript array with all the elements of the list, and access the at will on the client side (javascript)
2) access the "collaborateurs" via an ajax request

I would not recommend to mix server and client code like this through jsp.
Instead you should create a servlet and call what you need with ajax.
If you want to use a dirty/quick trick I think you can build back the array from the server side to the client side inside a <script> tag
For example:
<script>
var emailArray = [
<%for (int i = 0; i > collaborateurs.length; i++){ %>
"<%=collaborateurs[i].email %>"
<%
if(i < collaborateurs.length - 1){
%>, <%
}
}%>
];
</script>
(I wrote this by hand so I'm not sure the syntax is correct, but I hope you got the idea)

One more option you will have is converting your List object to json and then set it to a variable in jsp while compiling phase and the on client side parse json and make an object and iterate over it. This way you can access your list even after loading your page also.
You can use API like gson,Jackson etc.
Example :-
List<Object> list1=new ArrayList<>();
// Add values to list here
JSONArray obj=new JSONArray(list1);
In JSP :
var collaborateursList=${collaborateurs};
function showCollaborateurEmail(index) {
alert(collaborateursList[1].email);
alert(collaborateursList[2].email);
alert("collaborateursList[index].email);
}

Please verify the index is passing correctly to the function and try using this
alert("${collaborateurs[" + index + "].email}");

Related

Accessing a local js variable in razor block

I am trying to write razor code inside javascript where I am trying to use a local variable inside the razor code. Here is the sample code:
<script type="text/javascript">
for (i = 0; i < data.result.length; i++) {
$("#member-table tbody").append("<tr>");
var id = data.result[i].MemberId;
var actions = $("<td>" + #Html.ActionLink("Detay", "Edit", new { id }) + "</td>)");
}
</script>
the problem is that id is not recognized by the razor code (i.e. it does not exist in the current context). How can I achieve that ? Is there any way ?
It's not possible to access a javascript variable in a razor block.
That's because razor is executed in the server, and javascript is executed in the browser.
However, by looking at your code it seems like you are using javascript to populate a table and that's bad, there are two patterns for solving this problem, one that solves everything in the server, and another one that solves everything in the browser.
Solving everything in the server:
If you decide that you want to solve everything in the server, your javascript should request the contents from the server and load them into a placeholder without changing them, something like:
$("#myButton").click(function(){
$("#myDinamicDiv").load("/Path/ToView");
});
and then you use razor's foreach loop to generate the table's html:
#foreach (var x in ViewBag.MyData)
{
<tr>
<td>Generate contents here, including links </td>
</tr>
}
Solving everything in the client:
As pointed out in another answer, if you are using the default routing, you can just create direct strings in the javascript code and add them to your page, keep in mind however, that when using this solution, as your page gets complex, your javascript will became less and less maintainable, having a for loop that iterates over data is a sign that maybe you can benefit from javascript UI frameworks like Angular.js and Knockout.js, in fact, what you are doing is the core of Knockout.js's third lesson in its tutorial (Single page applications)
If you're just using default routing, then simply just don't bother with the Razor #Html.ActionLink. Stick with an explicit tag:
var actions = $('<td>Detay</td>');
...obviously with whatever your current controller name is substituted for [your-controller-here].
(And I'm assuming your 'id' isn't necessarily URL-encoded, hence the 'escape'.)
You are mixing server side and client side here. You cannot create #Html.ActioLink using client side variables. Html.ActionLink is rendered on the server, it does not have any clue at all about your client side variables.
If you want to use a client side variable, like "id", render a plain html link (a) tag.
This worked for me once
if ('#ViewBag.DownloadLink' != '') {
window.location.href = '#ViewBag.DownloadLink';
}

How to Put Data coming through Request or session into JavaScript Code in a JSP Page

I am making a Project where the need is to query no of already booked seats from database and show those seats as already booked in the layout made on a JSP page using JavaScript.
I have made a query in database & I have the data. All the data is joined by "," using Join() function.
Example:- 3,6,8,10
Now how to put that data dynamically into Javscript code existing on a JSP Page? The Javascript Code where I want to put the dynamic data (Not Posting Full Java Script Code, Posting Only The Exact Part)
<script>
var bookedSeat = [5,10,25]; // << Put Dynamic Data Here
seats(bookedSeat);
</script>
I have tried using <% --- %> but it didn't work. Can someone please help me? I am very new to JavaScript.
You can easily use those Request or Session data in JavaScript using EL. You can try like below code:
<script>
var bookedSeat = ${variableName}; //Put variable name which you are setting in request or session
seats(bookedSeat);
</script>

how to pass javascript variable to embedded Server Side code ASP.NET WebForm

let say i have a function like below in BAL.cs file
public static void xyz(string name)
{
Response.Write("Hello "+name);
}
Let say i have a javascript variable x.
now i want to call the function from BAL.aspx file
<script>
var x= "Tahmid";
<%=BAL.xyz()%> // want to pass x as a parameter
</script>
this is in webform.
It seems like there is some sort of confussion here that I would like to help solve. Server code and client code are separated. When client code executes (such as javascript) the server has no way to know what happened so your server side code (code behind) is not aware of any changes. In order to have the javascript variable information on the code behind you'll need to send that variable value back to the server and one of the mechanisms is the one provided by user2952502. I think in your case a postBack (using a submit or link button) would be more appropiate, right? I think you're trying to redraw the page based on something that the user did (since you're using javascript).
I think we should have some more information to understand the whole scope of your question and probably suggest you a better way to deal with it.
so you want to use windowfunctioname ?
since javascript is clientside and asp is serverside you could create a list of calls with parameters.
<script type="text/javascript">
var calls = [{exec: 'functionname', param : {name: 'Tahmid'}}];
document.addEventListener('DOMContentLoaded', function () {
c = calls.length;
for (var i = 0; i < c; i++) {
call = calls[i];
window[call.exec](call.param);
}
});
</script>
I hope that was an answer that helps.
The question is not clear enough .
what are u trying to do ?
just to print a dynamic text u can do with javascript function..
if u have to use a server function please specify the platform u use : MVC / WebForms..
in MVC you can use jQuery Post:
<script>
var x = "value";
$.post('#Url.Action("Action","Controller")',{name : x});
</script>

Get guid values with js and razor

I have an Asp.Net mvc 3 project
I'm using razor, and need to generate guids in javascript
I was trying this:
<script type="text/javascript">
$(document).ready(function () {
function getNewGuid() {
return '#Guid.NewGuid()';
}
I'm using inside the click event for a button, but the second call to the function is returning the same value
What should I do for reevaluating the function with each call?
The
#Guid.NewGuid()
is evaluated server-side when the page is rendered, so you will always get the same value.
You need a Javascript Guid library from somewhere.
Try the accepted answer to this question.
While you could make an Ajax call to the server, it's pretty pointless if all you're after is a unique value that could be generated far more efficiently client-side.
Create a controller then use JSON to return a new Guid from the server. Then use $().ajax to get the value.
If you don't want to ask the server for one use the following answer
Create GUID / UUID in JavaScript?

Wanting to mix server side ASP.Net MVC expansion in javascript file, but how... RenderPartial?

I have some common javascript functionality that I want to share across several views/pages.
However I want to put some C#/ASP.net into the javascript - pulling in some data from the server.
It seems like the best option is to use a partial page, and include the javascript in that.
Just wondering if there is a javascript equivalent of the partial page?
Or is there another/better/alternative way of doing this?
EDIT:
I realise I could use ajax to pull the server code in (although how do I refer to the server, Url.Content won't work) but this code is to handle page permissions, ie the server data details what functions the user can access and the javascript functions are then used to show/hide buttons based on that. So the data needs to be present early on rather than triggering the page to be built after the ajax callback happens.
Thanks in advance,
Chris
I usually put some data that is needed by javascript into the top of the page.
I have it in the Masterpage.
After that I include the common js files. The variables defined at the top of page are available to the scripts.
Don't forget to JavascriptEncode these values. Html-Encode is not enough, it doesn't handle the '. Use Web Protection Library for it http://wpl.codeplex.com/.
<script language="JavaScript">
var controller = <%= AntiXss.JavaScriptEncode(ViewContext.RouteValues.GetRequiredString("controller")) %>;
var userRightRead = <%= AntiXss.JavaScriptEncode(Model.UserRightRead) %>;
</script>
However I want to put some C#/ASP.net
into the javascript - pulling in some
data from the server
You don't need to put any C#/ASP.NET into javascript to pull data from the server. You can simply use AJAX. Example with jQuery:
$.ajax({
url: '/home/someaction',
success: function(data) {
alert(data);
}
});
I'll normally wrap the javascript up in a class and then pass in the view model values I need.
For example with this javascript:
var testClass = function(config){
this.width = config.width;
this.height = config.height;
this.showDimensions = function(){
alert( this.width + " by " + this.height);
}
}
the view/partial view would contain:
<script>
var dim = new testClass({
width: <%=Model.Width %>
height: <%=Model.Height %>
})
dim.showDimensions();
</script>

Categories

Resources