How do you set a textbox value to the equivalent of DateTime.Now in Javascript? I tried these
$('#LastUpdatedTime').val('<%= System.DateTime.Now %>');
$('#LastUpdatedTime').val('<%= System.DateTime.Now.ToString() %>');
Both set the value to the literal string <%= System.DateTime... instead of the time.
Add a javascript function in the aspx which simply returns the server tag, then call this function from your .js file. i.e. in the ASPX add:
function GetTimeNow () { return '<%= System.DateTime.Now.ToString() %>';}
You can't put server tags in a javascript file.
You have to put the code in a file that is handled by the ASP.NET engine, e.g. your .aspx file.
(It's possible to configure the server so that the ASP.NET engine also handles .js files, but that's not a good solution. Javascript files are cached more extensively than regular pages, so it's not certain that the server executes the code each time the file is used.)
Do you have them inside <script> tags on the aspx page?
The aspx page should look something like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
//put your JAVASCRIPT here
$('#LastUpdatedTime').val('<%= System.DateTime.Now %>');
$('#LastUpdatedTime').val('<%= System.DateTime.Now.ToString() %>');
</script>
</form>
</body>
</html>
That code is fine. The problem is that your <%= System.DateTime.Now %> code is not being parsed as server side code. What's the rest of the page look like?
Edit:
Since it's in an external JS file, you could always rename the ".js" file to ".aspx" so that ASP.Net would start processing it. Then you'd just have to change your <script> tags to use the ".aspx" name instead.
The other option is to configure your server to send ".js" files through the ASP.Net handler.
How about writing out the time on the main .aspx page in the header
<script type="text/javascript">
var now = <%= System.DateTime.Now %>;
</script>
and then doing
$('#LastUpdatedTime').val(now);
You just need to make sure that you name things appropriately so that the JS in the external file gets the value from the global scope.
Related
Currently I have the following code in Visual Studio asp.net. It seems like I'm making a new function in the head, while I want to use the one written in the aspx.cs file. The color is not working as I intended, but I'll get back to that.
It could look something like this:
//<script type="text/javascript" src='<%= Active_Frozen(string text, string color) %>'></script>
<head>
<script type="text/javascript">
function Active_Frozen(text,color)
{
document.write(text,color);
}
</script>
</head>
<body>
<script type="text/javascript">
Active_Frozen(text,color);
</script>
</body>
public Tuple<string,string> Active_Frozen(string text, string color) {
connection();
string query = "SELECT CustomerInfo FROM ActiveSubscription WHERE UserName=#UserName";
SqlCommand cmd = new SqlCommand(query, conn);
if(query=="true")
{
text = "Active";
color = "Green";
}
else
{
text = "Frozen";
color= "Red";
}
return Tuple.Create(text, color);
}
EDIT: The reason I have the code in my aspx.cs file is because HTML does not support string hence why it's needs to be amoung the server code. That's why I need to reach the function from the aspx file since I need the text to contain two different options.
Not that way, but you can ofcorse use that specific function in your aspx page, if you bring its implementation here (on aspx page). You can even have all the code in you aspx file. (kind of a single-file page). You Actually want to implement Embedded Code Blocks in ASP.NET Web Pages. Here's an example:
<%# Page Language="C#" %>
<script runat=server>
protected String GetTime()
{
return DateTime.Now.ToString("t");
}
</script>
<html>
<body>
<form id="form1" runat="server">
'Current server time is' <% =GetTime()%>.
</form>
</body>
</html>
But in general, using embedded code blocks for complex programming logic is not a best practice, because when the code is mixed on the page with markup, it can be difficult to debug and maintain. In addition, because the code is executed only during the page's render phase, you have substantially less flexibility than with code-behind or script-block code in scoping your code to the appropriate stage of page processing.
If you want to call code behind function from aspx, the class is public and the function is public static, and as long as you've imported the namespace in an <%# Import %> directive.
user server tag to call server side methods:
<body>
<% Active_Frozen(text,color); %>
</body>
In default.aspx I have:
<form id="form1" runat="server">
<div>
<asp:Button ID="clikme" runat="server" Text="click me" />
</div>
</form>
In default.aspx I have:
clikme.Attributes.Add("OnClick", "javaScript: return myfunction();");
And in JScript1.js I have
function myFunction() {
alert('this is my function');
return false;
}
The above code does not work it shows 'Microsoft JScript runtime error: Object expected'. I can't figure out how to find a solution.
You are call function with wrong name myfunction() should be myFunction() as javascript is case sensitive. Also make sure you include the JScript1.js in the current aspx file. You can read this MSDN artile to learn how to include js file.
clikme.Attributes.Add("OnClick", "javaScript: return myFunction();");
To include js file
<script type="text/javascript" src="yourDirectorIfAny/JScript1.js" ></script>
try this
add
script type='text/javascript' language="javascript" to your js portion and place your function inside it..
try
clikme.Attributes.Add("OnClientClick", "javaScript: return myFunction();");
The best way is to give reference of javascript file on Aspx page itself as suggested by Adil. If you want to register some javascript methods in code behind then you can have a look at this example.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerclientscriptblock.aspx
Something like below will helpfull..
string script = "myFunction();";
AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", script, true);
JScript is CASE SENSITIVE language.
clikme.Attributes.Add("OnClick", "javaScript: return myfunction();");
function myFunction() {
...
}
Check above lines. myFunction function must be equal.
jQuery and JavaScript can manipulate DOM like anything. But if C# has to send something to the client, then in my knowledge, we can only user Response object to write something in the browser. Now, this would write text in the browser, but we do not have control over where would it write it. Is there anyway that we can control from C#, somehting like :
"This is the text and I want it to be innerHTML of some particular DIV"?
You have two ways to go about doing something like this.
Make your div runat="server" and then it's accessible from the back end to manipulate
Register a JavaScript call using ClientScriptManager.RegisterClientScriptBlock and manipulate the div that way.
But also as Chuck has mentioned in his comment - that's a rather odd thing to do in ASP.NET. For the most part you'd use Label, Literal etc. server controls to add and manipulate text on a page instead of modifying native DOM elements directly.
That's not really how the internet works. When your browser navigates to a webpage, it sends a request to a server. The server responds with something. If it's trying to show a whole webpage, it needs the HTML of the whole page back. C# is powering the webserver.
When you browse to another page, you're not modifying an existing page; you're getting a whole new page back. We use JavaScript to get around that by letting it put out calls to webservers and use the information it gets back to modify the HTML on page, which it does know about, because it's running client-side.
So: no.
You can set the inner html of a div from your code behind. Just ad a runat="server" attribute to the div
<div id="divUserInfo" runat="server"></div>
and in your code behind
string strHtml="<h3> User Name </h3><p>User description</p>";
divUserInfo.innerHtml=strHtml;
This is in VB.NET, but I am sure C# has an equivalent. Just inject some javascript to do what you want.
ClientScript.RegisterStartupScript(Me.GetType, "myScript",
String.Format("<script>document.getElementById('{0}').innerHTML = '{1}';</script>", elementID, html))
.NET provides frameworks to do this - check out WebForms or MVC
From this article on MSDN:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Message.InnerHtml = Server.HtmlEncode("Welcome! You accessed this page at: " + DateTime.Now);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>HtmlContainerControl Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="Message" runat="server"></span>
</div>
</form>
</body>
</html>
I would like to know how to run a javascript function on page load.. in my asp.net page. I do not want to do it in from my .cs file OnLoad, I want to keep it in the aspx page if at all possible.
I am new to javascript so any ideas?
<html>
<head>
<script type="text/javascript">
function loadJavaScript()
{
// add code here
}
</script>
</head>
<body onload="loadJavaScript()">
<h1>Java script on load demo</h1>
</body>
</html>
There is a nice example here
or
<script type="text/javascript">
$(document).ready(
function() {
//your code here
});
</script>
Add an onload event to the body html element.
http://www.w3schools.com/jsref/event_body_onload.asp
You can use the HTML body onload event.
or
Use a javascript framework like jQuery and use the $(document).ready() event. .ready()
You can use the RegisterStartupScript to register your javascript snippets from the code behind:
http://msdn.microsoft.com/en-us/library/bb310408.aspx
The "Header control" we use holds a jquery reference. When I attempt to leverage any jquery functionality from the Master page it fails because the jquery reference has not been added yet.
Is there a way to force the Header Control that is embedded into the Master Page to load it's resources before the Master Page attempts to reference them?
I'd include the jquery reference in the head of the master page itself.
Or if you don't want the jquery on every page then you can do this in your master page:
<head runat="server">
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
And then do this on the aspx page that needs jquery:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</asp:Content>
Either way you do it accomplishes the same thing. It includes the jquery file in the "head" of your HTML. And that's the easiest way to ensure jquery works properly.
You can use the ScriptManager in the template master to register your javascript inclue file for JQuery.
You can use
ScriptManager.RegisterStartupScript or
ScriptManager.RegisterClientScriptInclude
Another way is in the template master, in the oninit method use this code
Page.Header.Controls.Add(new LiteralControl(" <script src="jquery" type="text/javascript"></script> "));
You could simply move the JQuery script reference into the aspx of the master page itself (at the top, of course). Then, any controls would be able to access JQuery.