Differences between Script & Code behind? - c#

Please let me ask something. I just confused for what is the difference of javascript, JQuery and code behind attributes.
for example :
ASPX
<tbody id="toggleSup" runat="server">
C#
toggleSup.Visible = false;
--------------------------------------- OR ---------------------------
C#
CallScript((string)(Session["toggle"]));
private void CallScript(string str)
{
string scriptx = "<SCRIPT LANGUAGE='javascript'>";
scriptx += "toggle('" + str + "');";
scriptx += "</script>";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scriptx", scriptx, false);
}
Script
function toggle(para1) {
if (para1 == 0) {
$('#toggleSup').hide();
}
else {
$('#togglePO').hide();
}
}
for these two difference things, most of the developers use script. Why? Actually C# code is only one row. different thing is if I use script, no need to use runat="server" but if I used code behind, need to use runat = "server". So I think there may be definately have advantages. Please explain me, if possible...
Thanks

If you say toggleSup.Visible = false; in your C#, then the toggleSup does not even get rendered to the DOM. Meaning it's not on the page at all. If you want to make that element visible from some action on the page, then you have to make a round trip to the server and re-render all (postback) or part (ajax) of the page.
Alternatively, if you allow the toggleSub control to be manipulated from JavaScript (jQuery in this case), then it's part of the DOM and can be acted upon in response to other events on the page. Mainly, this means that the client browser can do things without asking the server for more HTML.
So, the C# method looks simpler to code, but the jQuery method is more flexible if you need a rich client-side experience.

When using "script", the browser performs the work. With runat server, then the browser must either get/post a HTTP request or do "AJAX" to the server.
Using "script" is much faster and is easier to maintain state.

In simple words Java Script and JQuery code runs on the client browser whereas C# code runs on the server.

Related

How to Run JavaScript Function on page load

I have a program(c#) but the programs needs to work for every timezone, so i created a js script to know the client timezone and this is what i get (and it works) but only if only click action(example button), but i need this to work (run) on my page load is that possible?
This is my script
<script type="text/javascript">
function pageLoad() {
myFunction();
}
function myFunction() {
var localTime = new Date();
var year = localTime.getYear();
var month = localTime.getMonth() + 1;
var date = localTime.getDate();
var hours = localTime.getHours();
var minutes = localTime.getMinutes();
var seconds = localTime.getSeconds();
var calculated_date = hours + ":" + minutes + ":" + seconds;
var div = document.getElementById("demo");
div.innerText = calculated_date;
var client_date = document.getElementById("client_date");
client_date.setAttribute("value", calculated_date);
}
</script>
And this is what i tryed so far
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
Thanks anyway for reading my post, hope someone can help on this issue
Yes, it is possible. All you need is to use onload() event.
This would do it
<body onload="myFunction()">
<!-- body elements here -->
</body>
You can execute any function that you want to execute on a page load. I used myFunction because that had to be executed when the page loads.
with javascript
if (document.readyState === "complete") { myFunction(); }
with jquery
$(document).ready(function(){ myFunction(); });
The problem isn't what you think. In all likelihood, this JavaScript *is*set to run when the page loads. And it's probably going to do exactly what you told it to do. The problem is what else you're doing. Note these three lines:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
What you're doing here is:
Set the JavaScript to run when the page loads.
Capture the value of a TextBox from before the page loaded.
Abandon the page entirely and redirect to another page.
So even if the JavaScript code would run, you're not capturing the value it sets. And even if you were capturing that value, you abandon the entire page before it even loads and redirect the user to a different page.
You need to better understand the difference between server-side code, which runs on the server in its entirety before delivering a page to the client... and client-side code, which runs after a page has loaded on the client.
If you need this information from the client, you'll need to get it from client-side code. This code will need to run in a loaded page and then send the value back to the server in some way. Either the page has to execute and then perform the redirect from client-side code, or (probably better) the page can run as normal, make an AJAX post to the server to notify you of this information (time zone), and then the server can respond to the AJAX request with any data the client-side code needs to adjust the page accordingly.
It's not really clear what you're customizing based on the time zone or when you need to know the time zone. But it is clear that you need the client-side code to execute before you can retrieve that value from the client.
Use System.Web.ScriptManager Like this :
Page.ClientScript.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "myFunction();", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
Well you can't store the value within a hidden field and then read result, but what you can do is store the timezone offset as a cookie and then read that on the server after the page reloads.
This article explains it perfectly
http://prideparrot.com/blog/archive/2011/9/how_to_display_dates_and_times_in_clients_timezone

Automated system for opening other website links in new window/tab

I have a website, in which when user clicks a link it opens up in the same window if it is of my website's page, else in new window if domain is different. But I am doing this manually like this:
Open Link
checkdomain() checks the domain name of the link and returns true if it's of my website else false. I used the code from [ HERE ] for this purpose.
My question is: Is there any efficient and client side way available for checking link domains and open up them in new windows/tab if of another website(domain)? Like a JavaScript solution will be better, but then again JavaScript can be disabled by user. So, is there any other solution? Even JS solution will be great. Ignoring the disabling by user.
Somewhere on the page, or in an external JS file:
function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href")
&& anchor.getAttribute("rel")
&& anchor.getAttribute("rel").indexOf("external") >= 0)
anchor.target = "_blank";
}
}
window.onload = function() {
externalLinks();
};
Then, any external links just need to have rel="external" in the markup. For example:
Click here!
The main advantages of this approach is that you're not going to cause any validation errors, even with an XHTML Strict doctype. Users are also able to easily prevent links opening in new windows by simply disabling JS.
If you need the decision of external/internal to be made automatically (and client-side), you can alter the logic of externalLinks to base the decision on the href attribute rather than the rel attribute. Of course, if you've already got the external/internal logic functioning in your codebehind, I would recommend using that information to render the anchor with the appropriate semantics (with rel), rather than re-writing almost identical code in your client-side JS.
Try comparing your link url's host part (www.wrangle.in) with following in you function logic.
string currentURL = HttpContext.Current.Request.Url.Host;
I do not recommend to compare the name (i.e http or https), you can split using substring function.
For Client side
var homeURL = document.location.hostname;
$('a').each(function() {
if ( $(this+'[href*='+homeURL+']')) {
$(this).attr('target','_self');
}else{
$(this).attr('target','_blank');
} });
This link may help you to understand Url Parts.

Set C# Property Value by Javascript

I have a C# Property CategoryID, I want to set it's value in Javascript.
I am trying to set the value CategoryID like below:
var sPath = window.location.pathname;
var catId = null;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if (sPage == 'xyz.aspx')
{
<%=CommonUtility.CategoryID=4%>;
}
else if(sPage == 'zxy.aspx')
{
<%=CommonUtility.CategoryID=5%>;
}
But by this method I always get the value of CategoryID= 5(which is in else block) .
Please suggest me how can get the Property value based on condition.
You can't set a C# property from a client-side (js). You may use ajax to do some work, but you simply can't manipulate server-side code.
edit:
if you still wonder how it's possible you get a value, see Mike's explanation of that fact. But the truth remains. You can't. It's impossible. If you want to know the longer explanation, see how asp.net actually works, it's lifecycle etc. Simple way of putting it would be like this:
A user sends a request to the server using his browser. The server receives it, creates a requested page and instantiates needed classes etc. Then it's gets parsed and sent to the client as html (and other resources of course, like images, css...). The instantiated page class CAN'T be accessed and modified afterwards by the client, because it's already flushed by the server. Every request creates a new instance. There's no way of interacting js with c# anyway. Can you imagine what it would be like, if you could use some js to modify C# on a remote server? It doesn't make sense at all.
You cannot set properties in your code-behind using client-side script this way. The only way to do something like that would be to use AJAX to send data to your server, although I'm pretty sure that's not appropriate for your case.
When you call <%=CommonUtility.CategoryID = 4%>, the server actually executes that statement when it is parsing the page before it sends it to the client. The reason that the property value is 5 is that both of those statements get executed, regardless of the logic in your Javascript if block. Your client side code will not actually be executed by the browser until the server has already parsed both of those tags, which at that point it would be too late to accomplish what you want anyways.
Is there any reason that you simply can't do all of this in the code-behind on page load? Is there some reason you feel like this has to be handled in JS?
Edit:
If you are unable to access the code-behind file (.aspx.vb or .aspx.cs) then simply use a server script block in the top of your .aspx page
<%
If (Request.Path.ToLower().Contains("xyz.aspx")) Then
CommonUtility.CategoryId = 4
ElseIf (Request.Path.ToLower().Contains("zxy.aspx")) Then
CommonUtility.CategoryId = 5
End If
%>
You can't set the C# variable from client script, because all the server code runs first, then the page is sent to the browser.
The client code will end up looking like this:
var sPath = window.location.pathname;
var catId = null;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if (sPage == 'xyz.aspx')
{
4;
}
else if(sPage == 'zxy.aspx')
{
5;
}
}

Receive data from PostBack in JavaScript

I'm using jQuery to make postback then in my .ascx file I have code like this:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
var dataItems = args.get_dataItems();
alert(dataItems['ctl00_cphContent_articleList_tbUpdate']);
}
}
Where on the Internet can I find specification of args object? What methods has it got?
Second, why do I have to pass in my server side data into control using ScriptManager?
Code on the server side is:
ScriptManager.GetCurrent(this.Page).RegisterDataItem(tbUpdate, DateTime.Now.ToString());
and tbUpdate is the control on the site.
Is there any more elegant way to get access to data sent back to the client side. Do I have to send this data to any control? What does it really mean that data is sent to control?
How can I consume this data from that control? I had to use Firebug to find the id of the control and get access to it.
It sounds like you're trying to do an AJAX call to the server, and use the resulting data client side to either inject into an existing control, or create new controls for the data from the server.
I can only suggest you read these articles that explain how this works in far more detail than I can go into in an answer here:
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
and
http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
These are the clearest and most concise documents I have found on the subject.

Why Response.Write behavior varies in the given scenario?

When i POST the page using the following code, the Response.write("Hey") doesn't write the content ("Hey") to the parent page
<form method="post" name="upload" enctype="multipart/form-data"
action="http://localhost:2518/Web/CrossPage.aspx" >
<input type="file" name="filename" />
<input type="submit" value="Upload Data File" name="cmdSubmit" />
</form>
But When i use following code , and POST the data, the Response.write("Hey") can be obtained in the parent page
HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://localhost:2518/Web/CrossPage.aspx");
requestToSender.Method = "POST";
requestToSender.ContentType = "multipart/form-data";
HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;
using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
{
fromSender = responseReader.ReadToEnd();
}
In the CrossPage.aspx i have the following code
if (!Page.IsPostBack)
{
NameValueCollection postPageCollection = Request.Form;
foreach (string name in postPageCollection.AllKeys)
{
Response.Write(name + " " + postPageCollection[name]);
}
HttpFileCollection postCollection = Request.Files;
foreach (string name in postCollection.AllKeys)
{
HttpPostedFile aFile = postCollection[name];
aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName));
}
Response.Write("Hey");
}
I don't have any code in the Page_Load event of parent page.?
What could be the cause? I need to write the "hey" to the Parent page using the first scenario. Both the application are of different domain.
Edit: "Hey" would be from the CrossPage.aspx. I need to write this back to the Parent Page
when i post using the form action, after processing the Page_Load() event in CrossPage.aspx, the URL points to "http://localhost:2518/Web/CrossPage.aspx" which means the application is still in the CrossPage.aspx and didn't move to parent page.
You almost hit on the reason yourself:
when i post using the form action, after processing the Page_Load() event in CrossPage.aspx, the URL points to "http://localhost:2518/Web/CrossPage.aspx" which means the application is still in the CrossPage.aspx and didn't move to parent page.
Your form takes the user to CrossPage.aspx, so the parent page is gone, now the previous page in the user's history.
It sounds like you are trying to do some sort of asynchronous file upload. Try looking for AJAX file upload examples, something like this: How can I upload files asynchronously?
Probably it is because you have the code in an
if (!Page.IsPostBack) block? this code will be executed only the page is not loaded on a post-back.
(HttpWebResponse)requestToSender.GetResponse(); will trigger a GET request, that's why your code is working when you call Crosspage.aspx using that code.
You are treating the page like a service. E.G. Start at ParentPage.aspx > pass data to ServicePage.aspx for processing > write response back to ParentPage.aspx for display.
You got it to work with C# by passing the duty back to the server, where state can easily be maintained while crossing page boundries. It's not so simple when you try to solve the problem without C#. This isn't a Winform app. As NimsDotNet pointed out, changing the method to "get" will get you closer, but you will get redirected to CrossPage.aspx and lose the calling page.
You said you are on "different domains". By this I think you mean your using two different IIS servers. The C# solution should still work in this scenerio, just as you've shown. Just add a Response.Write() of the fromSender object. There's nothing you've told us that makes this not technically possible. Still, if you want a client side solution you could use javascript to make the get request without getting redirected.
This post shows you how to make a get request with JQuery.
I say your aFile.SaveAs(Server.MapPath(".") + "/".... is throwing an exception. try commenting it out and testing it.
UPDATE:
I'm guessing it works from a HttpWebRequest because there is no file being posted therefore the file loop is skipped. when posting from the HTML you have a file input so your file loop is getting used and resulting in the save logic being executed. so again, that leads me to think it's your save logic
Also,I think you have a try catch statement wrapped around all this that is catching exception so u have no idea what's going wrong. If that's the case, never do that. You rarely ever want to catch exception.
After quick glance at ur save logic, replace "/" with #"\". Server.MapPath(".") returns the path using back slashes not forward slashes.
I would suggest changing CrossPage.aspx into an .ashx HttpHandler. The Page.IsPostBack may not be working correctly because it is expecting ViewState and other hidden ASP.net form fields that tell it that it's a post back from an ASP form. You also don't need to go through the whole Page life cycle functionality that ASP.net Webforms goes through.

Categories

Resources