I need to get a JavaScript variable from my code behind without doing a page refresh or a button click event. Here's my code:
aspx:
<asp:HiddenField ID="docLengthValue" runat="server" />
<script type="text/javascript">
var body = document.body,
html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
//alert(height + ": Page length");
document.getElementById("<%=docLengthValue.ClientID%>").setAttribute("Value", height);
</script>
c#:
//Skrollr body tag background parallax animation
string docLengthVar = docLengthValue.Value;
HtmlGenericControl skrollr = (HtmlGenericControl)this.Page.Master.FindControl("bodyBG");
skrollr.Attributes.Add("data-0", "background-position: 0px -120px;");
skrollr.Attributes.Add("data-" + docLengthVar, "background-position: 0px 0px;");
dataAttb.Text = "This is the Document length: " + docLengthVar;
How can I access the Value field of the <asp:HiddenField ID="docLengthValue" runat="server" />? I know that the JavaScript compiles after the C#, but is there a way to get this variable?
Jeff-
This is not really going to be an answer, and I apologize but I think you may be quite far off course here.
Your recent post history seems to indicate that you want a parallax effect on your web page. The posts I am referencing: 1 and 2.
Have you followed this tutorial? Where along it have you had a problem?
General
I think you have some confusion about how the your web pages are working. WebForms is a ASP technology, or active server page. You can read more about this but basically it provides a platform which you can more easily develop responsive web sites.
The JS you are writing is a technology that runs entirely in the browser. When the JavaScript runs the code has no idea that it is in an ASPX page. It has no idea how to talk to the code behind.
When your page renders it is pure and raw html that the client receives. Through the magic of the platform when the user submits the form or clicks a button your code behind runs. But that is nothing you can't do on your own. All that is happening is your browser is sending properly formatted HTTP requests, and your web server is dispatching those to pages (code / class(es).
Relation to your problem
You are trying to animate a background image on a web page. That is an entirely client side job. You do not want the client to be talking to the web server frequently enough to create a smooth transition. In reality it is likely impossible.
The stuff you are looking at is pure JavaScript and runs entirely in the browser. I highly encourage you to pursue that as the avenue to solve your problem. And then ask questions as you have problems with that.
Edit: Apologies if I have inferred too much. My suggestions are in earnest.
Related
I have a textarea tiny_mce such as
<textarea id="Textarea1" name="abc" rows="15" cols="80" style="width: 80%">
</textarea>
I want to set it in page load.
If i add runat server , this change to "pure textarea" that is not tiny_mce control.
How can i set content from c sharp?
Keep in mind that TinyMCE is a JavaScript-based editor that runs 100% in the client - there are no server side APIs to talk to TinyMCE.
The API to load content is a JavaScript API that runs in the browser:
https://www.tinymce.com/docs/api/tinymce/tinymce.editor/#setcontent
If you want to use this API you need to pass the data from the server to the browser and then call setContent() with that data. You can throw the data into a JavaScript variable, make an AJAX call to fetch the data as the page loads - you have several choices.
If you want to do this server side the only option is to place the HTML inside the <textarea> tag. Something like:
<textarea>
<p>text < text</p>
</textarea>
A major complication with this approach is that the HTML you place in the <textarea> needs to be escaped as in my example above. This is not a requirement when using the setContent() API.
UPDATE: If refreshing sometimes make this work you likely have a timing issue - you are likely trying to use TinyMCE APIs before the editor is initialized. If your goal is to load content when TinyMCE is loaded you can use something like this in the TinyMCE configuration:
setup: function (editor) {
editor.on('init', function () {
// Your AJAX call to get the content
this.setContent(variableWithTheContent);
});
}
This function will not get called before the editor is initialized so you can be sure that APIs like setContent() will work at that point.
i have a doubt that i can redirect the page , but can i put height and width there
response.redirect("Mypage.aspx");
for eg
response.redirect("Mypage.aspx",height="300px",width="200px");
i am doing this in asp.net, c#
You cannot open a page with this method, use javascript window.open instead.
ClientScript.RegisterStartupScript(this.Page.GetType(), "", "window.open('Mypage.aspx','mywindow','menubar=1,resizable=1,width=300,height=200');", true);
dude, you quite lost... I suggest you to understand the server side concept of web application first, otherwise the learning asp.net experience could be frustrating...
regarding your question, there is not such thing what you want to do, the display on the page is html format in the client side (applying style(for example) to html elements )
although you can map those html ui in the server side
I have a MasterPage which will appear in every page in the application and I'm trying to load a "LoginBox" which uses PageMethods inside a Div tag in this MasterPage
So far I have tried doing as I would do on a Content Page, tried converting it into a User Control and tried using a server side include (< !--#include file="LoginBox.aspx"-->)
None succeeded.
I can see with firebug that the webresources get loaded but the PageMethods javascript isn't created in any of those methods.
I am REALLY trying to avoid having to create a WebService for this, and moving the LoginBox is not an option, I would rather drop the MasterPage idea, but then maintenance would become hell.
I need ideas or a direction on this.
Any help is appreciated
I got it working successfully with an iframe loaded from javascript, to me it's an ugly solution, but still one. I'm open for better solutions
<script type="text/javascript">
(function () {
var e = document.createElement('iframe');
e.setAttribute("src", "LoginBox.aspx");
e.setAttribute("scrolling", "no");
e.setAttribute("frameborder", "0");
e.setAttribute("height", "73px");
e.setAttribute("width", "225px");
e.setAttribute("marginheight", "0px");
e.setAttribute("marginwidth", "0px");
e.async = true;
document.getElementById('loginboxd').appendChild(e);
} ());
</script>
Looks to me like you're mashing classic asp with ASP.NET
the point of user controls is to encapsulate exactly what you are doing here.
even then however you will find your attempts to componentize your code will still lead to a messy mess mess. consider moving over to ASP.NET MVC if you can. with that you can do far more suitable and cleaner things to keep your codebase clean.
I have a pretty simple web-form set up in .Net where I am leveraging jQuery for some of the functionality. I am using the DOMWindow portion for part of the presentation layer.
There is a login form in a div that is set to display:none. When a user clicks a button on the page, it displays the login form. However the .Net button for the login form will not fire it's event when display is set to none. If i take this out, it fires fine. I have also tried using the visibility attribute, but no luck.
the div code is:
<div id="Login" style="display:none;">
The launching code is:
click here to login.<br />
the jQuery code is:
function LaunchLoginWindow() {
$(document).append("#Login");
$.openDOMWindow({
loader: 1,
loaderImagePath: 'animationProcessing.gif',
loaderHeight: 7,
loaderWidth: 8,
windowSourceID: '#Login'
});
}
Any help or explanation that anyone can offer is appreciated.
I noticed i had some code in there defining a client-side function on the Login div. I removed this so as to eliminate it as a possible issue.
I can see in your code that you are appending the div #Login but not setting its style property back to normal like block so. Set it back to block and i am sure it will work
try adding somthing like:
$(document).append("#Login").show();
OK, after playing around with this using firebug, I found the issue: When the jQuery plug-in DOMWindow creates its display layer, it appends to the HTML node of the DOM, which places the control outside the asp.net form tag. Therefore the button and actions associated with it via the DOMWindow are not recognized by .Net. So i edited the DOMWindow source file to append to the DOM form node rather then the html node.
The drawback is that the source has now been customized and will have to be QA'd thoroughly, especially if any further changes are made. But I hope to manage this effectively via commenting in the file.
Hope this helps anyone else who hits this issue.
pbr
This question got me thinking about how one might go about doing the relatively undoable: seamlessly integrate server-generated HTML from ASP.NET with client-side control via javascript. Sure, you can always use javascript/jquery/libraries to create the same display client-side. But much of the time, it's easier to do all the rendering on the server instead of just passing data to a client-side control which must handle the user interface and rendering. Or maybe you've already got a lot of less-interactive server code that you'd really rather not completely re-do using javascript libraries to just add some better interactivity.
I had a theory which seems to work in a basic proof of concept. Suppose you want to completely re-render the HTML of a server-generated control based on a client-side event, without posting back. So using jquery, I have a page:
default.aspx:
<a id="link1" href="#">Click Here</a>
<div id="container">
<asp:PlaceHolder id="MyPlaceholder" runat="server" />
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#link1').click(function() {
$.ajax({
url: "default.aspx",
type: "GET",
dataType: "html",
async: true,
data: { "ajax": "1" },
success: function(obj) {
// replace the HTML
$('#container').html(obj);
}
});
});
});
The event causes it to query itself with ajax. The codebehind that does the trickery is like this:
TestUserControl ctl;
string ajax;
protected void Page_Load(object sender, EventArgs e)
{
ctl = (TestUserControl)Page.LoadControl("TestUserControl.ascx");
Myplaceholder.Controls.Add(ctl);
ctl.OnRender += new TestuserControl.RenderHandler(ctl_Render);
}
protected void Page_PreRender()
{
ajax = Request.QueryString["ajax"] == null ? "" : Request.QueryString["ajax"];
}
void ctl_Render()
{
if (ajax == "1")
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (HtmlTextWriter writer = new HtmlTextWriter(sw))
{
ctl.DoRender(writer);
}
Response.Write(sb.ToString());
Response.End();
}
}
In TestUserControl, i expose base.render to get the output:
public void DoRender(HtmlTextWriter writer)
{
base.Render(writer);
}
Basically, if the page is called without the "ajax" querystring, it just acts like itself. But when that querystring is used, it intercepts the output stream from the content I am concerned with (a usercontrol called TestUserControl.ascx) and renders just that. This is returned to the client, which updates the HTML. All the IDs will be recreated exactly as before since I am not trying to render just that control in isolation, but in context of its own page. Theoretically, every bit of magic created by ASP.NET should be reproduced, retrieved and updated by the ajax query.
Apart from the obvious lack of efficiency, it seems to work swimmingly in this little test. I can completely rerender the control using the server generated HTML without a postback and I've written zero javascript. This example doesn't actually change anything, but it would be simple to pass more parameters to change the output.
I was wondering if anyone had tried anything like this in practice? What potential problems might I not be thinking of?
If server performance is not an issue, it seems like it might be quite easy way to get a heck of a lot of functionality with all the benefits of ASP.NET server controls. But I can't seem to find any discussion of using this technique in practice so I am wondering what I might be missing.
Well, for starters, you're sending a GET request to your page, so the control you want to update won't receive up-to-date form data. More importantly, ViewState will be lost and you probably don't want that, unless your user control is very simple.
You could work around the problem by using a POST request, but there are other potential issues, e.g. can you guarantee that the client scripts embedded in your user control either run again or don't when you update it, consistently, on all browsers?
Fortunately, others have already solved those problems. I'd suggest you place your user control inside an UpdatePanel and force a refresh from the client side:
__doPostBack("yourUpdatePanelClientID", "");
If the alternative is using an UpdatePanel, it's definitely worthwhile to consider partial rendering. Even if you're only updating a small portion of a page with the UpdatePanel, these updates must send the entire ViewState back to the server, the server must run the entire page through its life cycle, render it, and then extract the partial area. You take a significant performance hit for its convenience.
In your case, you're still incurring a page life cycle hit since you're rendering that partial within an ASPX pae. It's not as bad as the UpdatePanel, but unnecessary.
I've found that splitting the partial rendering out to a web service or HttpHandler handler works well. It's much faster than most other methods for rendering partials in WebForms, but still allows the flexibility of using User Controls for templating.
The drawback is that controls inside the User Control cannot handle PostBacks. You can definitely re-render it and/or pass parameters in to control its rendering, but you can't use this to render a GridView and expect its paging links to work, for example.
I wish there was more discussion about the topic of moving ASP.NET web forms into the modern era. I've had to figure out most everything on my own. I personally strive for the simplest solutions, and avoid all solutions that require layering on even more Microsoft. Nothing against MS, I just want to keep it simple and use ordinary web standards.
So far, I've been able to AJAX down everything I've tried, using jQuery load. There are no pat, simple answers, but if you are persistent, you can probably solve any client side problem resulting from old school ASP.NET practices.
I think the number one most important thing to do is stop using ViewState. Completely. This will force you out of many terrible practices that would cause you problems on the client. This is actually easier to do than you might think. And at that point, AJAXing stuff down will usually just work. Even DataGrids. Do your own paging, whether client- or server-side, it's not that hard, and then you can reuse your solution everywhere.
The problems will come from third party stuff that you have no control over. In those cases you can make use of IE developer tools (F12) to see what ASP.NET was originally sending down. Worst case, you'll have to scrape out some JavaScript and run it yourself. In practice I rarely have to do anything that terrible. I suppose if you are using a lot of heavy weight controls this would be impractical, but in that case you've already bought the farm.