"The name does not exist in the current context javascript" + Window.Location - javascript

Using javasciprt function for performing the similar function as Response.Redirect.
function redirectToHome(sessionID) {
window.location = '<%= ResolveUrl("~/default.aspx") + "?SessionGUID="+ sessionID %>'}
Passing sessionID from codebehind:
string sessionId = system.guid.new().tostring();
btnClose.attributes.add("OnClick","javascript:function(redirectToHome("sessionId" ));");
Code maybe not exactly the same but i am doing pretty much above.
But at the page rendering its giving error message
"the sessionID does not exist in the current context javascript"
Please suggest another way of doing this.

In your redirectToHome function
window.location = '<%= ResolveUrl("~/default.aspx") + "?SessionGUID="+ sessionID %>'
The entire string is within <% ... %>, hence rendered by .NET before being passed down to the server. So sessionID there will be assumed to be a .NET variable, and whatever you pass to the javascript function will never be used. (Try "view source" so see what your code really renders like)
You need to either move sessionID outside of the .NET block:
window.location = '<%= ResolveUrl("~/default.aspx") %>' + '?SessionGUID=' + sessionID;
or generate the session id from the .NET block immediately when creating the function:
window.location = '<%= ResolveUrl("~/default.aspx") + "?SessionGUID="+ System.Guid.NewGuid().ToString() %>'
If you do decide to pass the session ID through the javascript variable, you have to make note of some additional issues:
Your code will currently print something like (assuming you've fixed the string concatenation issue):
onclick="javascript:function(redirectToHome(e4bd5302-a77c-40f4-9439-6b510bb4cdf3))"
This has a set of problems:
You don't need to specify javascript: in onClick as it is already a javascript-specific attribute.
You shouldn't wrap that code in function( ... )
You're not quoting the string ID
The correct call would look something like this:
btnClose.attributes.add("OnClick","redirectToHome('" + sessionId + "');");
Note that this could equally well be written as:
btnClose.OnClientClick = string.Format("redirectToHome('{0}');", sessionId);
which is perhaps more readable.

Related

Pass string variable in C# to javascript function for use in alert box

so what I'm trying to do is pass a simple string variable that contains my error message in C# into my javascript function when I call the function. My function call works fine, but it keeps outputting the wrong thing. This might be important too, I'm calling the Response.Write pieces within my Global.asax.cs file and my javascript file is within my Scripts folder in my MVC project. Based on the research I've found, this is what I currently have after help from the comments:
function KickOutUnwantedUsers(aMesssage) {
console.log("Inside KickOutUnwantedUsers"); //for debugging
console.log(aMesssage); //for debugging
alert(aMessage);
window.open('', '_self').close();
}
It just continues to output this
<%=errorMessage%>
I'm not sure how to fix it, as everything I've found says to pass the variable that way, but I'm wondering if I need to pass it as an actual parameter into the function, and if so, how to do that.
UPDATE: Here is the C# code:
else
{
string user = s.Remove(0, 4);
string errorMessage = "THE FOLLOWING ERRORS MIGHT HAVE OCCURRED: " + user +
" has either been disabled or the account does not exist." +
" PLEASE CONTACT YOUR ADMINISTRATOR. ";
Response.Write("<script type=\"text/javascript\" src=\"Scripts/HelpfulFunctions.js\">");
Response.Write("</script>");
Response.Write("<script type=\"text/javascript\">");
Response.Write("KickOutUnwantedUsers('" + errorMessage + "');");
Response.Write("</script>");
}
SOLVED
#Igor was very helpful in the comments, and I did things as he suggested, which for some reason would not work at first, but then the following day I deletedmy JavaScript file, remade it under the same name and retyped out the javascript code and it worked. Coding is strange sometimes. I must've had a typo or something.
This is what the (badly documented) HttpUtility.JavaScriptStringEncode is for:
// the second argument "true" causes quotation marks to be inserted as well
var message = <%= HttpUtility.JavaScriptStringEncode(errorMessage, true) %>;
First. Such line as
var message = '<%=errorMessage%>';
only makes sense in ASP.NET markup file. In js file it is meaningless, since javascript files are not processed by ASP.NET server-side.
Second. Since you are passing message string as parameter, you need function signature to reflect this:
function KickOutUnwantedUsers(aMessage) {
alert(aMessage);
window.open('', '_self').close();
}
and - note the quotes around the parameter value:
Response.Write("KickOutUnwantedUsers('" + errorMessage + "');");

Can I reference a Node JS function from JS within a <script> tag in a Jade template

I am building a blog with Node.js, Express and MongoDB. In my "create new post" template I have a title field and a slug field.
I am using the Slugs for Node.js from NPM: https://npmjs.org/package/slugs
What I am trying to do is:
dynamically take the value from the title text input using EventListener,
filter it through the slugs() function, and
add it to the value attribute of the slug text input.
So I would type "My favorite character is &" in the title field and the value in the alias field would dynamically change to "my-favorite-character-is".
I believe you have to do something like the accepted answer in this question:
JADE + EXPRESS: Iterating over object in inline JS code (client-side)?
However, that was more for referencing variables rather than executing functions. And it seems like that is preprocessed and then you can't access it anymore.
Is what I'm trying to do even possible?
Or should I go with something like this?
https://github.com/stipsan/String.Slugify.js
Here's what I tried to no avail:
!= "<script>"
!= "var post_title = document.getElementById('title');"
!= "var post_alias = document.getElementById('alias');"
!=
!= "var aliasValidator = function() {"
!= " this.value = " + slug( + "this.value" ) + ";"
!= "};"
!= "var titleValidator = function() {"
!= " post_alias.value = " + slug( + "this.value" ) + ";"
!= "};"
!=
!= "post_title.addEventListener({'keyup': titleValidator, 'keydown': titleValidator, 'change': titleValidator});"
!= "post_alias.addEventListener({'change': aliasValidator});"
!= "</script>"
And here's the view where the variable is passed:
var slugs = require('slugs');
newPost: function(req, res) {
return res.render('add-post', {
title: "Write new post",
slug: slugs,
dayDateName: tools.dayName
});
}
This should be pieced together with a few things:
Get yourself a sluggify function you can load into the browser as well as node. There are trivial ways to do this like copy/pasting the code into a public/slugs.js file, as well as more sophisticated things like browserify or RequireJS. Start simple, but to directly answer your question, no, you can't just magically call a function that exists within your node process from the browser directly but YES you can share the same function in both node and the browser using one of the aforementioned techniques.
In the browser, use events to take the title as it is entered, transform it, and populate the slug field. This is all browser-side JS and has nothing to do with template rendering or node
In your node code to handle the form submission, you'll also need to make sure the slug is valid be running it through the sluggify function again (here you can just use the npm module).
For jade, you don't need all those crazy != prefixes, just do this (this has no direct bearing on your question, just FYI).
script
var put = "your raw javascript here";
var jade = "knows what to do and you don't need prefixes or escaping";
The way you are writing your template, you seem to be implying the function will be executed on the client.
This is not possible.
Instead, you should use an ajax call back to your server to execute the slug function, or precompute all the values and send this to the client.

Can I mix & match javascript with server-side code in javascript?

I know this might be an odd situation but currently I need to mix javascript with server side code as follows:
function PerformGlobalCallback(sender, value) {
var index = hfCurrentTabIndex.Get("activeIndex"));
window['<%= ((ASPxCallbackPanel)myTabControl.TabPages[index].Controls[0]).ClientInstanceName %>'].PerformCallback(sender + "|" + value);
}
where hfCurrentTabIndex is a hidden field which correctly holds the value of the current tab index.
I know I cannot simply put the "index" variable in the <%= %> section so I need to come up with a way to do it.
The reason I need this is because the myTabControl current tab index is somehow lost in between callbacks. Also, even though I store it in Session, I get null when I access it in the above code.
Please let me know if you have any insights. Appreciate your help.
var clientInstanceNames = [];
<%
for(int x=0; x<myTabControl.TabPages.Count; x++)
{
Response.Write("clientInstanceNames[" + x.ToString() + "] = \"" + (ASPxCallbackPanel)myTabControl.TabPages[x].Controls[0]).ClientInstanceName + "\";");
}
%>
function PerformGlobalCallback(sender, value) {
var index = hfCurrentTabIndex.Get("activeIndex"));
window[clientInstanceNames[index]].PerformCallback(sender + "|" + value);
}
That should do what you want.
Server side code is processed first so the page gets sent to the client browser before the client browser processes the JavaScript. You could also use an AJAX call to get the .ClientInstanceName. But the way demonstrated above builds the JavaScript array on the server for you, so your client code just has to look-up the index.
Note The code was written inside my browser window and is not tested, so syntax errors may exist.
Yes.
Done quite regularly when setting up javascript with server-generated data.
var myjsVariable = "<%= SomeServerSideVariable %>'
But, the way you've done it wont work.
This bit is javascript (client side)
var index = hfCurrentTabIndex.Get("activeIndex");
But then you try to use that client side variable in a server-side call:
<%= ((ASPxCallbackPanel)myTabControl.TabPages[index].Controls[0]).ClientInstanceName %>
-----------------------------------------------^

Embed javascript Variable within ASP.NET MVC 2 tag

I have a Javascript statement in an MVC view that looks like this and works:
win.attachURL('<%: Url.Action("GraphDetails", "Dashboard", new { area = "Anglian", OSName = "Hello" }) %>');
When I try to extract the variable 'Hello' and put it into a javascript variable (id) and subsequently embed it into my tag like this, it breaks:
var id = "Hello";
win.attachURL('<%: Url.Action("GraphDetails", "Dashboard", new { area = "Anglian", OSName = "' + id + '" }) %>');
Question is, how do I embed a JS variable inside an ASP server tag, that itself is already embedded within Javascript? This is for a local prototype, security concerns are not an issue.
Thank you,
Tom.
One is server-side, the other is client-side, you can't mix the two.
When you do it on the server side with the id as a variable it will break because id doesn't exist in the server side context.
Why don't u try break up the statement on the client side?
var id = "Hello";
var actionInit = "<%: Url.Action("GraphDetails", "Dashboard", new { area = "Anglian"}) %>";
win.attachURL(actionInit + "?OSName=" + id");
Note: when appending ?OSName, this may cause some issue if your route doesn't map 100% correctly. eg. u get /Dashboard/GraphDetails?area="Anglian" and u append another "?" that will be an invalid URL. On the other hand, it will also be invalid if your route matches 100% and you append "&OSName". So just check that out first
I don't think you can in general. In this case at least the <%: ... %> part is evaluated at page load time and will never run again.
Instead, you can compute this in JavaScript, e.g.
var id = "Hello";
var baseURL = '<%: Url.Action("GraphDetails", "Dashboard",
new { area = "Anglian" }) %>';
win.attachURL(baseURL + '&OSName=' + id);
However that makes assumptions about how you're assembling your routing parameters for that route. You could use Url.Action to generate the full route with a dummy value and then substitute, e.g.
var id = "Hello";
var baseURL = '<%: Url.Action("GraphDetails", "Dashboard",
new { area = "Anglian", OSName="ZZZ" }) %>';
win.attachURL(baseURL.replace('ZZZ', id);
but then there's a subtle chance this could go wrong, particularly if you're feeding user generated string into other parameters in the string where they could hit on the value you substitute.
If you really did want to run Url.Action again you'd have to make an AJAX call back to a known URL with the parameters to get the URL, which is overkill really.

Best way to get server values into JavaScript in .NET MVC?

Using ASP.NET MVC + jQuery:
I need to use some values owned by the server in my client-side JavaScript.
Right now, I've temporarily got a script tag in the actual view like this:
<script>
var savePath = '<%= Url.Action("Save") %>';
</script>
But I want to move it into something cleaner and more maintainable. I'm thinking of something along the lines of creating a JavaScript controller/action and returning a JSON object that would contain all the data I need, then using the view as the src for a script tag.
Any other ideas?
This actually depends. For simple inliners, the line above works just fine. If you need a LOT of server data in the JavaScript, your view approach may work. However you'll get the same result if you just render partial view that outputs the required JavaScript.
There's a problem with this, since you may end up mixing server data with JavaScript. The best approach would be to minimize server data to absolute minimum, and pass it to JavaScript functions instead of mixing with JavaScript code. That is, not
function func() {
var path = '<%= Url.Action("my") %>';
$(".selector").append("<img src='" + path + "' />");
}
but
function AppendImageToSelector(path) {
$(".selector").append("<img src='" + path + "' />");
}
function func() {
var path = '<%= Url.Action("my") %>';
AppendImageToSelector(path);
}
This makes the code cleaner and easier to understand, helps to move JavaScript out to separate .js files, helps to re-use JavaScript when needed, and so on.
If you need a lot of server-related URLs in JavaScript, you may want to create global (in master page) function like
function url(relative) {
return '<%= Url.Content("~") %>' + relative;
}
and use it from JavaScript scripts. This technique is questionable, though; for example it doesn't use MVC routing rules so URLs may not be out of sync; etc.
I know this is not applicable in all cases but when I need to pass an Url to a client script (as in your example) it is often to ajaxify some anchor or button I already have in the DOM:
<%= Html.ActionLink("Save data", "save") %>
and in my script:
$('a').click(function() {
$.get(this.href);
return false;
});
Stephen Walther - ASP.NET MVC Tip #45 – Use Client View Data

Categories