<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
' The first time the page loads,
' render the DefaultView.
If Not IsPostBack Then
' Set DefaultView as the active view.
MultiView1.SetActiveView(DefaultView)
End If
End Sub
Sub LinkButton_Command(sender As Object, e As System.Web.UI.WebControls.CommandEventArgs)
' Determine which link button was clicked
' and set the active view to
' the view selected by the user.
Select Case (e.CommandArgument)
Case "DefaultView"
MultiView1.SetActiveView(DefaultView)
Case "News"
MultiView1.SetActiveView(NewsView)
Case "Shopping"
MultiView1.SetActiveView(ShoppingView)
Case Else
Throw New Exception("You did not select a valid list item.")
End Select
End Sub
</script>
what is difference between above code in(aspx) And if the same code in code behind(aspx.cs). Difference between function defined in tag with runat="server" attribute and function defined in code behind...?
How to execute JavaScript Function From ASP.NET Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="How_calljavascript_aspx_page.aspx.cs" Inherits="How_calljavascript_aspx_page" %>
<!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">
<title>Call JavaScript in asp.net page by C# on page load </title>
<script type="text/javascript">
function MyFunction() {
alert('this is javascript function run by C# code.');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
execute JavaScript from code behind in asp.net:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class How_calljavascript_aspx_page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("alert"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"alert", "MyFunction();", true);
}
}
}
Functionally there is no difference between these two approaches, both will work the same for you.
Page script is useful if you have a small server side code, so that you can embed that code in the page itself.
But this will make things messier if the code is large.
The page designers will have access to the page code here.
The code behind approach provides you a clear separation of HTML and asp or VB code. Thats all...no functional difference between two approaches.
Related
I have following code in aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="test.aspx.vb" nherits="test" %>
<!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"></head>
<body>
<img src="images/loading_anim.gif" />Please wait...
</body>
</html>
In test.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
......Do some processing here .
Response.redirect("Next.aspx")
End Sub
Code Behind I do some processing in Page_load method and redirect to other page but it might take some time so I want to show user loading image.But it shows that after page_load is completed.How to handle this ?
I will suggest that you use a generic handler (ashx) and use un-buffered response. For example:
public class Handler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.BufferOutput = false;
context.Response.Write("<html><head></head><body><img src=\"images/loading_anim.gif\" />Please wait...</body></html>"
context.Response.Flush();
// do your processing
...
// redirect
}
...
}
Yet another way to first show image on the client side (using java-script) and then do redirection (or post) from client side.
I don't think it will work because always the server side code works first, then only HTML rendering starts. Better option will be using Ajax.
More details here : ASP.NET Integration with IIS 7
I need to set a single property in a jQuery command using a value that is calculated in the code-behind. My initial thought was to just use <%= %> to access it like this:
.aspx
<script type="text/javascript" language="javascript">
$('.sparklines').sparkline('html', {
fillColor: 'transparent',
normalRangeMin: '0',
normalRangeMax: <%= NormalRangeMax() %>
});
</script>
.aspx.cs
protected string NormalRangeMax() {
// Calculate the value.
}
It smells odd to have to call from the ASPX page to just get a single value though. Not to mention I have an entire method that does a small calculation just to populate a single property.
One alternative would be to create the entire <script> block in the code-behind using clientScriptManager.RegisterClientScriptBlock. But I really don't like putting entire chunks of JavaScript in the code-behind since its, well, JavaScript.
Maybe if I end up having many of these methods I can just put then in a partial class so at least they are physically separate from the rest of the code.
What method would you recommend as being easy to understand and easy to maintain?
The <% %> works fine. One thing that I do is set a value in a hidden field on the page (then writing the necessary javascript to extract that value), this is nice because I can change that hidden field via javascript and when/if the page posts back I can get that new value from code behind as well.
If you need to call the method on demand, you could do an jQuery AJAX call to a ASP.NET WebMethod to grab the data and re-populate the various options. You can find a good tutorial on how to do that here: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Below is some sample code using the hidden field method (using the datepicker control, but you'll get the idea):
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!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">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtCalendar" runat="server" />
<asp:HiddenField ID="hfTest" runat="server" />
</div>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ui.jquery.com/latest/ui/ui.datepicker.js"></script>
<script type="text/javascript">
var dateMinimum = new Date($("#<%= hfTest.ClientID %>").val());
$(function() {
$("#<%= txtCalendar.ClientID %>")
.datepicker({
minDate: dateMinimum
});
});
</script>
</body>
And the code behind Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
// Set Value of Hidden Field to the first day of the current month.
this.hfTest.Value = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).ToString("MM/dd/yyyy");
}
Personally, I would use the <% %> method. This is what the view is for. I don't like the RegisterClientScriptBlock at all. If you ever move to MVC you will get used to the <% %> ... :)
I ran into this problem a while back. I recommend <% %> for single variable stuff. I find the RegisterClientScriptBlock function useful only if I ever need the code-behind to determine which scripts to run.
Rick has a nice article about passing server vars to client script
The included script references, in particular jQuery, are being rendered after viewstate. Is there a way to get this in the < head>?
Page.ClientScript.RegisterClientScriptInclude("jQuery", "/scripts/jquery.js");
I am trying to register jquery.js in a user control's page load.
Thanks in advance!
P.S. If it can't be done (with ClientScript), anyone have an idea why they didn't build it in?
UPDATE
The main feature of the ClientScript manager I need is the ability to only include a script once. The control can appear many times on a page, but i only want one jQuery script include
to directly inlcude it in the HEAD:
HtmlGenericControl Include = new HtmlGenericControl("script");
Include.Attributes.Add("type", "text/javascript");
Include.Attributes.Add("src", sInclude);
this.Page.Header.Controls.Add(Include);
you would want to check to make sure its not there already before adding it.
I had this problem a while back, and I ended up not using RegisterClientScriptInclude.
I placed a placeholder in the header of the page, and added the script tag to the placeholder via a HtmlGenericControl.
I'll see if I can find my code and I'll edit my answer with it.
EDIT
I couldn't find my code, so I just re-created it:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!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">
<asp:PlaceHolder runat="server" ID="HeadPlaceHolder"></asp:PlaceHolder>
</head>
<body>
...
</body>
</html>
And the Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
HeadPlaceHolder.Controls.Add(/* Your control here */);
}
Hey, old question, but maybe this is still of interest for someone.
I am creating a own UserControl with .net 3.5sp1, ran into the same problems. Following solution works for me.
This code is from the UserControl class:
protected void Page_Init( object sender, EventArgs e )
{
const string scriptKey = "UserControlScript";
if( !Page.ClientScript.IsClientScriptIncludeRegistered( Page.GetType(), scriptKey ) )
{
Page.ClientScript.RegisterClientScriptInclude( Page.GetType(), scriptKey, ResolveClientUrl("~/js/UserControl.js" ) );
}
}
I used Page_Init because I need to do some more initialization that has to be done before Page_Load of the nesting page is called.
It appears its not possible to use Page.ClientScript to add scripts to the header of the page.
I have a web page where it will input an excel/CSV file from the user and read the data from it and import to DB.While inserting each record.I just want to show the details about the record being inserted to the user.(Ex : Client Details of A is adding...)
Try this... Set the output to unbuffered (Response.BufferOutput), and include some javascript in your page that updates the UI as you see appropriate. For example, it might update a SPAN with a percentage complete or the details of the record you are processing. Then in your server code, output <script> tags that call the Javascript function from the Render override. Make sure you call Flush() at the appropriate times, and also Flush the base code after it Renders... The JS function calls should get sent down at the appropriate times and executed on the client, resulting in an updating page.
For example... Your HTML page might look like this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!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">
<title></title>
<script type="text/javascript">
function UpdateScreen(t) {
document.getElementById('output').innerHTML = t;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id='output'></div>
</div>
</form>
</body>
</html>
<script type="text/javascript">
UpdateScreen('hello');
</script>
and your codebehind will look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
Response.BufferOutput = false;
base.Render(writer);
Response.Flush();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
Response.Write(string.Format("<script type='text/javascript'>UpdateScreen('{0}');</script>", i * 10));
Response.Flush();
}
}
}
}
I know this is an old question, and the owner of it may have moved on a long time ago. Anyway:
The proposed solution will not work on ASP.NET MVC. And if you ask me, which you don't, I'll say this is not the cleanest solution to the problem:
Here's a jQuery one,
And here's an IFrame one.
I have an ASP.NET 3.5 WebForm that leverages the frameworks Page.ClientScript.GetCallbackEventReference() method and I'd like some of the calls to be synchronous.
Now, the documentation says that the 5th parameter (see below) controls this. Specifically, when you pass 'false' it's supposed to be a non-asynchronous call. However, regardless if it's true or false, it still processes the call asynchronously.
Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context",false);
Is there a work-around for this or perhaps I'm doing something wrong?
ASPX Page
<%# Page Language="VB" AutoEventWireup="false" CodeFile="How-to-use-GetCallbackEventReference.aspx.vb" Inherits="How_to_use_Callback" %>
<!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">
<title>How to use GetCallbackEventReference</title>
<script type="text/javascript">
function GetNumber() {
UseCallback();
}
function GetRandomNumberFromServer(txtGetNumber, context) {
document.forms[0].txtGetNumber.value = txtGetNumber
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Get Random Number" onclick="GetNumber()" /><br /><br />
<asp:TextBox ID="txtGetNumber" runat="server"></asp:TextBox> </div>
</form>
</body>
</html>
Code Behind
Partial Class How_to_use_Callback
Inherits System.Web.UI.Page
Implements System.Web.UI.ICallbackEventHandler
Dim CallbackResult As String = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Me, "arg", "GetRandomNumberFromServer", "context")
Dim cbScript As String = "function UseCallback(arg,context)" & "{" & cbReference & " ; " & "}"
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "UseCallback", cbScript, True)
End Sub
Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
Return CallbackResult
End Function
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
CallbackResult = Rnd().ToString()
End Sub
End Class
For any other poor souls still using the MS AJAX library I found the following post:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/f4134c2e-ca04-423a-9da3-c613713a7b52/synchronous-callbacks-with-the-net-20-framework?forum=netfxjscript
The last comment from an MS source says:
This is actually by design. In order not to block the UI of the browser, this parameter doesn't actually do the request synchronously but makes sure the requests are queued and only one is going on at any given time. The effect is pretty much the same, except that the end-user can still use the browser UI while the request is going on and he won't have to kill the process if the server fails to respond or the network connection falls.
The MSDN page confirms this:
When sending data synchronously in a callback scenario, synchronous callbacks return immediately and do not block the browser. No two synchronous callbacks callback can execute at the same time in the browser. If a second synchronous callback is fired while one is currently pending, the second synchronous callback cancels the first and only the second callback will return.