Angle Brackets in Page head element - c#

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.

Related

How to change the Markup of a asp.net page serverside (from .cs file)

Thanks in advance.
We need to include or exclude IE conditional statements (which are in the header of the page) depending upon if a method(from the code behind) returns true or false. The Method is written in the code behind so if IfBrowserIsMobile() returns true , Markup related to IE conditional statement should not be present.
How do we achieve this ?
The Mark-up(in the header) is as follows-
<!--[if lt IE 9]>
<link rel="stylesheet" href="/css/lt-ie9.css" media="screen"/>
<![endif]-->
Include a literal control in head section of your aspx page and then in code behind you can set the Text property of this control to anything you like. This text could be html or non-html text. You can have as many such controls in the head section as you feel is necessary for your requirements.
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
In your situation you can include following code also in Page_Load event.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack && !IfBrowserIsMobile())
{
Literal1.Text = "<!--[if lt IE 9]>
<link rel="stylesheet" href="/css/lt-ie9.css" media="screen"/>
<![endif]-->";
}
}
If you want to emit JavaScript using a Literal control then use code-behind like below. The important thing is to include opening and closing script tags in this case.
Literal1.Text = #"<script type='text/javascript'>alert('hello sir');</script>";
Wrap it in an element which itself doesn't emit any markup, such as a PlaceHolder:
<asp:PlaceHolder runat="server" ID="ieLogic">
<!-- your client-side markup here -->
</asp:PlaceHolder>
Then in server-side code, just set its visibility depending on your condition:
if (IfBrowserIsMobile())
isLogic.Visible = false;
Generally you don't change the markup from server-side code, but you can conditionally show/hide different parts of the markup.

Calling JavaScript Function From CodeBehind

Can someone provide good examples of calling a JavaScript function From CodeBehind and Vice-versa?
You may try this :
Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);
Calling a JavaScript function from code behind
Step 1 Add your Javascript code
<script type="text/javascript" language="javascript">
function Func() {
alert("hello!")
}
</script>
Step 2 Add 1 Script Manager in your webForm and Add 1 button too
Step 3 Add this code in your button click event
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "Func()", true);
C# to JavaScript: you can register script block to run on page like following:
ClientScript.RegisterStartupScript(GetType(),"hwa","alert('Hello World');",true);
replace alert() part with your function name.
For calling C# method from JavaScript you can use ScriptManager or jQuery. I personally use jQuery. You need to decorate the method that you want to call from JavaScript with WebMethod attribute. For more information regarding calling C# method (called PageMethod) from jQuery you can refer to Dave Ward's post.
If you need to send a value as a parameter.
string jsFunc = "myFunc(" + MyBackValue + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);
You can not do this directly. In standard WebForms JavaScript is interpreted by browser and C# by server. What you can do to call a method from server using JavaScript is.
Use WebMethod as attribute in target methods.
Add ScriptManager setting EnablePageMethods as true.
Add JavaScript code to call the methods through the object PageMethods.
Like this:
Step 1
public partial class Products : System.Web.UI.Page
{
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<Product> GetProducts(int cateogryID)
{
// Put your logic here to get the Product list
}
Step 2: Adding a ScriptManager on the Page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
Step 3: Calling the method using JavaScript
function GetProductsByCategoryID(categoryID)
{
PageMethods.GetProducts(categoryID, OnGetProductsComplete);
}
Take a look at this link.
To call a JavaScript function from server you can use RegisterStartupScript:
ClientScript.RegisterStartupScript(GetType(),"id","callMyJSFunction()",true);
Another thing you could do is to create a session variable that gets set in the code behind and then check the state of that variable and then run your javascript. The good thing is this will allow you to run your script right where you want to instead of having to figure out if you want it to run in the DOM or globally.
Something like this:
Code behind:
Session["newuser"] = "false"
In javascript
var newuser = '<%=Session["newuser"]%>';
if (newuser == "yes")
startTutorial();
You cannot. Codebehind is running on the server while JavaScript is running on the client.
However, you can add <script type="text/javascript">someFunction();</script> to your output and thus cause the JS function to be called when the browser is parsing your markup.
You can use literal:
this.Controls.Add(new LiteralControl("<script type='text/javascript'>myFunction();</script>"));
Working Example :_
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage2.Master" AutoEventWireup="true" CodeBehind="History.aspx.cs" Inherits="NAMESPACE_Web.History1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function helloFromCodeBehind() {
alert("hello!")
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div id="container" ></div>
</asp:Content>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NAMESPACE_Web
{
public partial class History1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "helloFromCodeBehind()", true);
}
}
}
Possible pitfalls:-
Code and HTML might not be in same namespace
CodeBehind="History.aspx.cs" is pointing to wrong page
JS function is having some error
IIRC Code Behind is compiled serverside and javascript is interpreted client side. This means there is no direct link between the two.
What you can do on the other hand is have the client and server communicate through a nifty tool called AJAX. http://en.wikipedia.org/wiki/Asynchronous_JavaScript_and_XML
ScriptManager.RegisterStartupScript(this, this.Page.GetType(),"updatePanel1Script", "javascript:ConfirmExecute()",true/>
I've been noticing a lot of the answers here are using ScriptManager.RegisterStartupScript and if you are going to do that, that isn't the right way to do it. The right way is to use ScriptManager.RegisterScriptBlock([my list of args here]). The reason being is you should only be using RegisterStartupScript when your page loads (hence the name RegisterStartupScript).
In VB.NET:
ScriptManager.RegisterClientScriptBlock(Page, GetType(String), "myScriptName" + key, $"myFunctionName({someJavascriptObject})", True)
in C#:
ScriptManager.RegisterClientScriptBlock(Page, typeof(string), "myScriptName" + key, $"myFunctionName({someJavascriptObject})", true);
Of course, I hope it goes without saying that you need to replace key with your key identifier and should probably move all of this into a sub/function/method and pass in key and someJavascriptObject (if your javascript method requires that your arg is a javascript object).
MSDN docs:
https://msdn.microsoft.com/en-us/library/bb338357(v=vs.110).aspx
This is how I've done it.
HTML markup showing a label and button control is as follows.
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblJavaScript" runat="server" Text=""></asp:Label>
<asp:Button ID="btnShowDialogue" runat="server" Text="Show Dialogue" />
</div>
</form>
</body>
JavaScript function is here.
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
Code behind to trigger the JavaScript function is here.
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";
ScriptManager.RegisterStartupScript(Page, GetType(), "JavaFunction", "AlertError();", true);
using your function is enough
Try This in Code Behind and it will worked 100%
Write this line of code in you Code Behind file
string script = "window.onload = function() { YourJavaScriptFunctionName(); };";
ClientScript.RegisterStartupScript(this.GetType(), "YourJavaScriptFunctionName", script, true);
And this is the web form page
<script type="text/javascript">
function YourJavaScriptFunctionName() {
alert("Test!")
}
</script>
this works for me
object Json_Object=maintainerService.Convert_To_JSON(Jobitem);
ScriptManager.RegisterClientScriptBlock(this,GetType(), "Javascript", "SelectedJobsMaintainer("+Json_Object+"); ",true);
Since I couldn't find a solution that was code behind, which includes trying the ClientScript and ScriptManager like mutanic and Orlando Herrera said in this question (they both somehow failed), I'll offer a front-end solution that utilizes button clicks to others if they're in the same position as me. This worked for me:
HTML Markup:
<asp:button ID="myButton" runat="server" Text="Submit" OnClientClick="return myFunction();"></asp:button>
JavaScript:
function myFunction() {
// Your JavaScript code
return false;
}
I am simply using an ASP.NET button which utilizes the OnClientClick property, which fires client-side scripting functions, that being JavaScript. The key things to note here are the uses of the return keyword in the function call and in the function itself. I've read docs that don't use return but still get the button click to work - somehow it didn't work for me. The return false; statement in the function specifies a postback should NOT happen. You could also use that statement in the OnClientClick property: OnClientClick="myFunction() return false;"
I used ScriptManager in Code Behind and it worked fine.
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "CallMyFunction", "confirm()", true);
If you are using UpdatePanel in ASP Frontend.
Then, enter UpdatePanel name and 'function name' defined with script tags.
Thank "Liko", just add a comment to his answer.
string jsFunc = "myFunc(" + MyBackValue + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);
Added single quotes (') to variable, otherwise it will give error message:
string jsFunc = "myFunc('" + MyBackValue + "')";
You can't call a Javascript function from the CodeBehind, because the CodeBehind file contains the code that executes server side on the web server. Javascript code executes in the web browser on the client side.
You can expose C# methods on codebehind pages to be callable via JavaScript by using the ScriptMethod attribute.
You cannot call JavaScript from a CodeBehind - that code exists solely on the client.

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

Possible to do inline code in ASPX markup?

Is it possible to do things in a PHPish way in ASP.Net? I've seen <%= %> but I've tried it and couldn't get it to work.
The PHPish equivalent of what I want to do is
<script src="<?php echo ResolveUrl("jquery/js/jquery.js"); ?>"></script>
Yes, it's quite possible. You should familiarize yourself with all the variations of the (so called) alligator tags though.
Put code in between <% %> blocks. The <%= %> variant is a shortcut for Response.Write, and is used as a shortcut for directly outputting a variable to the page.
The following should work, as long as ResolveUrl is returning a string. Notice there is no ";" to end the line though.
<script src="<%= ResolveUrl("jquery/js/jquery.js") %>"></script>

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?

Categories