is there a way to process .NET/C# variables on external .js? - c#

I have my variable in an aspx.cs , such as :
protected string myVar="Hello";
Now, if I go to my scripts.js file added as :
<head>
<script src="/scripts/scripts.js" type="text/javascript"></script>
</head>
and I try this :
var myVarJs="<%=myVar&>";
it doesnt get the .NET myVar value.
Is there a way to catch it or am I dreaming?

Insert the variable before the script:
<head>
<script type="text/javascript"> var myVarJs="<%=myVar%>"; </script>
<script src="/scripts/scripts.js" type="text/javascript"></script>
</head>

You can also register/render client script. So you can declare variables in the backend and then render the javascript variables.

I don't think it is possible to directly access C# variable in javascript code.
As C# is client side and Javscript is server side.
Unless on the Asp.net page you save the variable in a hidden field or label as text which is not visible.
Asp:
<asp:HiddenField ID="hidden" runat="server" value="<%=strvariable %>" />
Javascript:
function Button_Click()
{
alert(document.getElementById('hidden').value);
}
So this would get the hidden field with the ID of "hidden".
This could work I think.

Related

How to call js file function from code behind page

I have following function in .js file and i need to call it from code behind page after saving a record.
I have registered scipt file in aspx page
aspx file
<script type="text/javascript" src="/scripts/visit-flash-report.js"></script>
.js file
function reloadDocTab() {
alert('hello');
$('#frmDocs').attr('src', $('#frmDocs').attr('src'));
}
Code behind page
I have tried the function but it is not working
Page.ClientScript.RegisterOnSubmitStatement(Me.[GetType](), "reload function", "return reloadDocTab();")
If I understand what your trying to do. You want to save the record on postback then when the page reloads call the javascript function.
Try this:
PageBody.Attributes.Add("onload", "reloadDocTab()");
Try this:
.aspx
<script type="text/javascript" src="/scripts/visit-flash-report.js"></script>
<asp:Literal runat="server" ID="litJS" />
.cs
litJS.Text = #"<script type='text/javascript'>alert('hello');</script>";
If you dont need to execute the script on a different postback you might want to assign an empty string to the literal.
Try one of these:
Page.ClientScript.RegisterStartupScript(this.GetType(), "ScriptKey", "reloadDocTab()", true);
OR
ClientScript.RegisterStartupScript(this.GetType(), "ScriptKey", "reloadDocTab()", true);
OR
ScriptManager.RegisterStartupScript(this.GetType(), "ScriptKey", "reloadDocTab()", true);
And i think you might need to refrence the .JS file in the head tag
<head runat="server">
<script src="~/scripts/visit-flash-report.js"></script>
</head>

JavaScript works locally but not when deployed to webserver

I'm deploying some code to a website and when I do the JavaScript does not run. I get the error:
SCRIPT5007: The value of the property '$' is null or undefined, not a Function object.
The code it is using is
#model MVCMasterDetail.DataAccess.cwwoLoadCurrentWorkOrderActualsResult[]
<script type="text/javascript">
$(document).ready(function () {
$(".grid-toggle").click(function () {
$(this).closest("table").find("tbody").show();
});
$(".hide-rows").click(function () {
$(this).closest("table").find("tbody").hide();
});
});
</script>
#Html.Partial("MasterDetailMasterPartial")
And what calls uses it is:
<td colspan="4"> Details<br/>Show- Hide</td>
Any help is appreciated.
Based off your comment in Ashley Ross's answer, it looks like your trying to add jQuery using a relative path. it also looks like you're using MVC. In MVC, the way you want to reference a file in html is:
<script src="#Url.Content("~/Scripts/jquery-1.7.1.js")"></script>
Also, it doesn't matter if your script tag goes in the head tag or not. The only difference it makes is loading. By putting it in the head tag, you're telling the browser to download the js file before it begins to load the body, which can be nice, but can also increase page load times. For faster page download, you actually want to put your script tags towards the bottom of your body tag, which defers downloading the js file until after the rest of the page has loaded. This results in faster page load times, but can cause some funky behaviors if you aren't anticipating it.
You need to include jQuery before any other scripts. It sounds like you have something like
<script type="text/javascript" src="customScriptThatUsesjQuery.js"></script>
<script type="text/javascript" src="jquery-x.y.z.min.js"></script>
instead of
<script type="text/javascript" src="jquery-x.y.z.min.js"></script>
<script type="text/javascript" src="customScriptThatUsesjQuery.js"></script>
Check that it appears in your HTML source before any other scripts that use it.
you have to add reference to jquery lib in <head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>

Angle Brackets in Page head element

Iam new to ASP.NET with prev. PHP experience (which meaby is causing this problem) and Iam having small problem passing data from codebehind to view-source.
I declared string variable on codebehind side such as:
...
public string mystring = "Scotty";
protected void Page_Load(object sender, EventArgs e)
{
...
So now I want to use it in view-code but when I put it in angle brackets (<%: or <%=) and put it in head element I got no access to this value. On the other hand when I put it in BODY element everything is ok.
My failing example (simplified):
<head runat="server">
<script language="javascript">
function beamMeUp()
{
alert(<%=mystring;%>);
}
</script>
</head>
<body>
<input type="button" onclick="javascript:beamMeUp" value="Warp6" />
</body>
Can anyone explain it to me why I can't use it (the <%=mystring;%>) in HEAD but i can use it in BODY ?
Best regards
The semicolon isn't necessary when using <%=. Think of it as writing:
<% Response.Write(mystring); %>
You will want to wrap that in quotes as well.
alert("<%=mystring %>");
Without quotes would be: alert(Scotty);
which does not make much sense unless you have a javascript variable called Scotty.
It should give you an alert box showing undefined
The code-behind variable mystring is available in the <head>. C# IntelliSense isn't displaying for it since it's inside of a <script> tag.
Your problem may be that you have
<head runat="server">...
I believe this causes ASP .NET to construct an HtmlHead object which you can reference from Page.Head. However, you cannot have inline constructs such as <% .. %> and <%= %> when doing this. I believe this is also true of other ASP .NET controls such as
<asp:TreeView ...>
<asp:TreeViewItem> <%= will cause error! %> </asp:TreeViewItem
</asp:TreeView>
http://geekswithblogs.net/mnf/archive/2007/11/14/code-render-blocks-not-always-work-inside-server-controls.aspx
You really had three problems:
1.) You have a javascript error as pointed out by the first responder when he told you to use:
alert("<%=mystring %>");
2.) You have an ASP .NET error because you can't use <%= %> inside a tag that has runat="server".
3.) Another javascript error in your onclick assignment. Note it is better to wire up events in code using attachEvent and addEventListener. Your onclick assignment does not need the javascript: in front. You might do this for an href attribute, but not an onclick. In the onclick, you are already executing javascript. You could have onclick="alert('yo!')" which would work. Also, when executing a function, you must include the parenthesis, so you should have onclick="beamMeUp();" (semi colon optional).
Your revised code should look more like:
<head> <!-- notice runat="server" has been removed -->
<script type="text/javascript">
function beamMeUp()
{
alert("<%=mystring;%>");
}
</script>
</head>
<body>
<input type="button" onclick="beamMeUp();" value="Warp6" />
</body>
Note: I tried the code above and it works. I made these changes
removed runat="server" from the <head> tag
added double quotes to alert("<%=mystring;%>");
changed onclick event to onclick="beamMeUp();" NOT onclick="javascript:beamMeUp".
Good luck.

Saving js file with c# commands

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link href="../../Content/css/layout.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/Areas/CMS/Content/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/Areas/CMS/Content/js/jquery.jeditable.js"></script>
<script type="text/javascript" src="/Areas/CMS/Content/js/jeditable.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".naslov_vijesti").editable('<%=Url.Action("UpdateSettings","Article") %>', {
submit: 'ok',
submitdata: {field: "Title"},
cancel: 'cancel',
cssclass: 'editable',
width: '99%',
placeholder: 'emtpy',
indicator: "<img src='../../Content/img/indicator.gif'/>"
});
});
</script>
</head>
This is head tag of site.master file. I would like to remove this multiline part from head and place it in jeditable.js file, which is now empty. If I do copy/paste, then <% %> part won't be executed. In PHP I would save js file as jeditable.js.php and server would compile code that is in <?php ?> tag. Any ideas how to solve this problem?
Thanks in advance,
Ile
In PHP I would save js file as jeditable.js.php and server would compile code that is in tag.
One thing to keep in mind here is that php is now forced to process that entire javascript file on every request. This is generally a "Bad Thing"TM, and it uses up server resources that could be spend elsewhere.
As Raj Kimal's answer already mentioned, what we do in ASP.Net to handle this in the most efficient way possible is have a short script defined inline with the page that does nothing but assign result of server code to variables. Do this before declaring other scripts, and you can then use these variables in those scripts directly. That way, you don't have to do any extra server work for your external javascript files.
I'll make one addition to Mr Kimal's answer. It's often best to enclose these variables in an object, to help avoid naming collisions. Something like this:
<head runat="server">
<script language="javascript">
var ServerCreated = {
ArticleAction:'<%=Url.Action("UpdateSettings","Article") %>',
OtherVar:'some server data'
}
</script>
</head>
Then your jeditable.js file would look like this:
$(document).ready(function() {
$(".naslov_vijesti").editable(ServerCreated.ArticleAction, {
submit: 'ok',
submitdata: {field: "Title"},
cancel: 'cancel',
cssclass: 'editable',
width: '99%',
placeholder: 'emtpy',
indicator: "<img src='../../Content/img/indicator.gif'/>"
});
});
Define your variable part as a js variable.
var foo = '<%=Url.Action("UpdateSettings","Article") %>';
and place it before the js reference. Then use the varible in your js file.
You can put the script inside an .aspx file and set the content type to text/javascript in the #page directive. You will still be able to use the code tags.
The cost of processing the entire javascript file every request can easily be mitigated by applying server side caching so that shouldn't be a problem. This can be configured in the #page directive as well.
You have a few options, but the key here is that if you need to use the <% %> syntax to get information you need to be in the context of an ASP.NET page.
You "could" move the actual function to an external file, and reference the JS, then add a small inline script block that called the function with two parameters, but that defeats the purpose of what you want.
The real question here, why have the overhead of an additional HTTP request for a single method?

ASP.NET Dynamic JavaScript File

I'm writing a ASP.NET web application. It dosen't use Web Forms or MVC. It uses ASP.NET Routing to a Http Handler, and the handler just writes html to the HttpContext.
The final output of my html is something like this:
<html>
<head>
<title>...</title>
<script type="text/javascript">
...
</script>
</head>
<body>
...
</body>
</html>
Now, Instead of writing the (long) script into this page, I want to write it to another page, and then use the src of script element to reference it. The problem is, that the script is dynamic.
<html>
<head>
<title>...</title>
<script type="text/javascript" src="..."></script>
</head>
<body>
...
</body>
</html>
Any ideas?
Thanks.
Can't you just place the location of the dynamic script inside the src?
I.e., if http://www.example.com/foo is your HTTP handler, can you make another HTTP handler, http://www.example.com/bar for the dynamic javascript? You should be able to pass any parameters needed inside a query string.
your script is dynamic => I assume it changes based on the user/context/date/time ??
you should set your Response.Charset (to UTF-8) & Response.ContentType (to text/javascript)

Categories