Get guid values with js and razor - javascript

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?

Related

DotNetBrowser calling a JS function and returning a value from C#

I see the option where you can initiate the function call in .NET and return a value, but I don't see an option where you are able to initiate a function call in javascript calling a .NET function and then return a value to javascript, similar to what would happen if I was using ASP.NET or hitting a Web API.
So basically here is what I am doing. I have a modal that pops up when the user clicks to save game. They enter the name of the Save Game file, click OK and it calls a .NET function to check the DB to see if it's a duplicate save game file or not. If it is, it should return "Error! Duplicate file name! Please choose a unique file name." If it is unique it saves the information to a DB and returns a "Successfully saved game!" message, waits 2 seconds and then redirects to the main dashboard page.
I have everything working fine up until the point .NET is supposed to return the value. Currently the modal window just sits there and nothing returns to JS.
I have it set up like I normally would through calling the .Net function and using .then(function (response) to get the response value, but it is coming back as undefined.
I'm sure there has to be a way to do this, I just don't see how in the documentation as that only shows how to do it when initiating the function call from .NET...
EDIT: OMG...I just realized this was such a dumb question...I'm already doing that returning lookups from the database...the answer was to set it equal to a variable instead of trying to chain the function onto the end.
THIS:
var value = window.CRUD.Save(fileName, model);
if(value === "Duplicate!") ....
INSTEAD OF:
window.CRUD.Save(fileName, model).then(function(response) {
});
The article by the following link explains how to call .NET from JavaScript:
https://dotnetbrowser.support.teamdev.com/support/solutions/articles/9000109869-calling-net-from-javascript
Thank you for adding your answer to the question as an update.

Access to Java model List from Javascript/JQuery dynamically

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

Call a PHP Link with Onclick

This isn't a duplicate question by any means and I have tried a lot finding solutions.So, please read it before down voting.
Background:
This application is like a note-taking web app where you can post/delete your notes.
Each item in the list has an id which is needed when making a delete call.
In my application, I have to delete individual items from a list which is generated by looping over a JSON response (by a REST API) using PHP.The JSON response can be obtained after successful login.
Question:
To implement delete functionality I have to send id of each of the items as a parameter to the rest api delete call.
So, for this I have to generate dynamic links of the form :
http://localhost/myfolder/api/notes/:id
which should be passed to the delete.php function (Which I have implemented in CURL).
I searched for possible ways :
Using a PHP function: It seems to be complex, however if there is some way to invoke a PHP function (the delete code using CURL) on click of a link (Which I found not possible as per some answers ?) this could be a great solution.
Using Javascript: I have to call a function upon click of link that sets a variable $_SESSION["id"] to the current item["id"] and then goes to delete.php where I use the $_SESSION variable to first set up the link and then use the CURL code.
I tried basic implementation using the second approach but I have hit a roadblock in this issue. It would be great if you could tell with a bit of code which approach should be followed or any other way to do this ?
This functionality is present in twitter/facebook and almost every such service, how do they implement this, the basic approach should be the same, right: Generate dynamic links and pass them to a php script on click ?
Basic Javasript approach :
<script>
<script>
var el = document.getElementById('del1');
el.onclick = del1;
function del() {
// I have to set $_SESSION here
return false;
}
</script>
echo "<a href=\"delete.php\" title=\"Delete\" id=\"del1\">";
//Here, I have to pass the item["id"] to the javascript function.
I had tried some other ways but I have modified the code a lot so, I can't post them. Thanks for your help.
Regarding #2, you can't access the user's session from Javascript, so that will not work.
My preferred way (if using jquery) is to put the id in a data attribute of the delete button (or the block as a whole). Then in the delete onclick function do something like
<div class="block" data-itemid="<?=$item['id']?>">
...
<div class="delete_button">Delete</div>
</div>
...
$('.delete_button').on('click',function(event) {
block = $(event).target.parent('.block');
itemid = block.data('itemid');
$.post('delete.php',[itemid: itemid]...);
});

passing dynamic parameters in script.aculo.us

I want to pass dynamic values inside parameters of script.aculo.us for auto suggestion in my jsp page
Below is my code where i want to get the value of checkbox and pass it to server. But in server side jsp its printing as it is ( i.e instead pf checkbox value its printing document.getElementById("mgmtsystem").checked )
<div class="auto_complete" id="object_name_auto_complete"></div>
<script type="text/javascript">
new Ajax.Autocompleter('<%=name%>', 'object_name_auto_complete', '<%=request.getContextPath()%>/component/ajax_introdata', { parameters: 'suggEnable= document.getElementById("mgmtsystem").checked' })
</script>
In above code i'm trying to send the value of document.getElementById("mgmtsystem").checked but its just passing it as same instead its value
If you copied your javascript into the question as it is on your code - this is why
This code does not let document.getElementById(....) get evaluated and treats it as a string
{ parameters: 'suggEnable= document.getElementById("mgmtsystem").checked' }
Try this
{ parameters: 'suggEnable='+document.getElementById("mgmtsystem").checked }
Or better yet use the utility methods built in to PrototypeJS
{ parameters: 'suggEnable='+$("mgmtsystem").checked }

I replace HTML using javascript, but that contains a form, want to keep value of that form

I have a page that I have a page I pull from the server every x seconds using some ajax, and then I replace some HTML on the site with the new HTML pulled from the server. The problem has always been that there is a form in that HTML. I want to know is there a way to preserve the value of the form (that the user has entered) when replacing the html in javascript.
Use two callback functions (you should use $.ajax), in the callback before sending (beforeSend(x){ /your code here/; }) you save the parameters (to an array or hashtable): saved = $(element).val(); then in the second callback (use success(x){}) you write them back in. using $(element).val(saved);
var save = document.getElementById('userForm').value;
//replace HTML
document.getElementById('userForm').value = save;
Two ways,
Send and then replace the value in the HTML on the server
Using JavaScript, save it in a session: http://www.webreference.com/authoring/languages/html/HTML5-Client-Side/
I'd say the best solution would be to combine the two and save a session on the server, then load it each time you load the HTML.
-Sunjay03

Categories

Resources