Saving js file with c# commands - c#

<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?

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>

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

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.

Loading complete Html-page in contentpane of aspx-page

here at home I have different projects and libraries for which I've created an helpfile with Sandcastle.
Now Sandcastle provides also the possibility to create a website.
What I would like to do is to create an aspx-page where I can dynamically create a menu and where the existing helpfile-websites can be sollicited. All in one place.
Is it possible to accomplish this? Maybe some control that I can use to view an entire webpage?
Thank you.
EDIT:
Seems I can't get it to work in an ASP-page for whatever reason, but probably because of the way Sandcastle creates the help-pages.
I've now tried it with a WinForm-application with a webbrowser-control and this approach works, so I guess this will be the way I have to go here.
But I do need to say thanks to Alison (and Leon) for their help regarding this issue.
Their solution works for "normal" html-pages, but (unfortunately) not for the ones I have.
For that reason, I've accepted the answer so others could benefit from it.
Updated
Take a look at jQuery load. You can have a div on your page and load the html from an external page into it. The load function can grab individual pieces of HTML from a different page.
On your main page, add this html:
<div id="myexternalpage"></div>
On the different page, add a div tag with an id around the content you want to grab like:
<div id="myexternalcontent">Test</div>
The add the following to your head tag:
<script type="text/javascript">
$(document).ready(function() {
$('#myexternalpage').load('myexternalpage.html #content');
})
</script>
Notice the addition of the "#content" selector to the end of the load function? This will have jQuery load the different page and return only the content in the div with id="content".
Using jQuery load will let you load the content once the page loads and you won't need to use any iFrames. You can use CSS to handle the height/width and handle any overflow.
I've made a quick and dirty test-page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test2.aspx.cs" Inherits="Test2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js " ></script>
<script type="text/javascript">
$(document).ready(function () { $('#myexternalpage').load('WebHelp/KoenHoefman/ExhangeRateWebService/Index.html'); })
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="myexternalpage">
</div>
</form>
</body>
</html>
But I get an error on the script line.
Microsoft JScript runtime error: Object expected
Do I have to replace document with something (probably a stupid question but I'm not used to use javascript)?
Update:
Added Leon's code and now it shows something. But when I want to use the page I really want to show (which is located in a subfolder) I get only the items on the index.html. The page that should be loaded into the IFrame of that page isn't shown. Also the pictures that are located in the same folder are not shown.
Error: HTTP 404
Requested URL:
/html/aea04102-3d0d-cf0d-f5f4-5634f5f06aed.htm

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