I have a simple Web Form with code like this:
//...
//tons of text
//...
<a name="message" />
//...
//tons of text
//...
<asp:Button ID="ButtonSend"
runat="server"
text="Send"
onclick="ButtonSend_Click" />
After POST I want to navigate user to my anchor "message". I have following code for this:
protected void ButtonSend_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterStartupScript(this.GetType(),
"navigate",
"window.location.hash='#message';",
true);
}
This simple JavaScript is not working in Firefox 3.5.2 - url is changing in browser but page is not navigated to anchor. In IE 8 it works perfectly.
Why this JavaScript code is not working in Firefox? Am I missing something?
I've solved my problem. JavaScript code was called before my anchor even existed. That's why Firefox wasn't scroll page down.
My code looks now like tihs:
this.ClientScript.RegisterStartupScript(this.GetType(),
"navigate",
"window.onload = function() {window.location.hash='#message';}",
true);
After page load I'm calling my simple JavaScript function.
The key to found solution was Cleiton answer. Firebug reports that getElementById was returning null reference. Then I looked at generated HTML like andrewWinn suggested - JavaScript was called before anchor existed. Made little googling and found solution.
Thanks for your answers!
Mendoza, you can use native scrollIntoView function.
To do what you want, just write:
this.ClientScript.RegisterStartupScript(this.GetType(),
"navigate",
"document.getElementById('id_of_the_element').scrollIntoView();",
true);
I ran into this once. Have you taken a look at the actual HTML? If I remember, FireFox was being case sensative on the anchors. I don't know if that changed recently or not.
You could try using the jQuery LocalScroll plugin. Using this, you could scroll using:
$(function() {
$.scrollTo("#message");
});
Or with your ASP.NET code:
protected void ButtonSend_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterStartupScript(this.GetType(),
"navigate",
"$(function() { $.scrollTo('#message'); });",
true);
}
It's not an ideal solution, especially if you're not using jQuery anywhere in your project already, but it might solve your problem.
Related
i have a very annoying problem...
i had a textbox and a link in my master page. i wanted to use the link button to pass the text of textbox as a query string for some filtring stuff.
but i understood that the cod behind of link bottun doesnt work at all and it just refresh the page.
i tried to do it by jquery by window.location.href but it only worked at the first page and other pages couldnt get the postback.
i changed everything and tried to use radsearchbox.
this control works fine but it only works in every page except the main page.
let me be more clear:
it works great onhttp://kalashabakeh.ir/product.aspx?groupID=1&subgroupID=0
but it doesnt work at www.kalashabakeh.ir
i really dont know what can couse so many problems. maybe my script manager or a js file or something?
plz help me!
here is my current code with radsearchbox:
in masterpage.master:
<telerik:RadSearchBox runat="server" ID="RadSearchBox2"
CssClass="searchBox" Skin="Silk"
Width="200" DropDownSettings-Height="300"
DataSourceID="SqlDataSource_search"
DataTextField="product_name"
DataValueField="product_key"
EmptyMessage="جستجو..."
Filter="Contains"
MaxResultCount="20"
OnSearch="RadSearchBox2_Search">
</telerik:RadSearchBox>
in master page codebehind:
protected void RadSearchBox2_Search(object sender, SearchBoxEventArgs e)
{
Response.Redirect("product.aspx?searchID="+ e.Text.ToString(),false);
}
Is it a typo or something like that. Your Rad searchbox control ID is RadSearchBox2 and it's calling a event handler named RadSearchBox2_Search whereas you are having a handler method named RadSearchBox1_Search. See below pointed
<telerik:RadSearchBox runat="server" ID="RadSearchBox2"
.....
OnSearch="RadSearchBox2_Search"> <--Here
</telerik:RadSearchBox
protected void RadSearchBox1_Search(object sender
^-------- Here
i finally found the answer...
as people discussed here
its a kind of a bug in iis7...
this code solved my problem thank to Eric
just add this code in master page.
public void Page_PreRender(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.Page.Form.Action) && Request.Url.AbsolutePath.ToLower().EndsWith("/default.aspx"))
this.Page.Form.Action = "Default.aspx";
}
Now i can light up my cigurate ...
I have a popup in my page which I am trying to show on dropdownlist selected index changed event.
Here is register statement
ClientScript.RegisterClientScriptBlock(GetType(),"id", "ShowApplicationPopUp()",true);
Here is my javascript function
function ShowApplicationPopUp() {
$('#NewCustomerMask').show("slow");
$('#NewCustomerApplicationPopUp').show("slow");
}
Both of my divs are initially hidden by using display:none; statement.
The problem is when my dropdownlist is changed the popup is not seen at all.I tried putting an alert statement to check if the function is called , and the alert statement is fired.Any ideas as to what I am doing wrong.
Any suggestions are welcome.
Thanks.
When you use RegisterClientScriptBlock the Javascript code is inserted early in the page, so it will run before the elements are loaded.
Use RegisterStartupScript instead, which places the code at the end of the form.
I too could not get this code to work but thanks to the above I now have working code. Note, I have a linkbutton inside an Ajax Update Panel.
in my code behind aspx.cs page is:
protected void OpenButton_Click(object s, EventArgs e)
{
// open new window
string httpLink = "../newWindow.aspx";
ScriptManager.RegisterStartupScript(this, GetType(), "script", "openWindow('" + httpLink + "');", true);
}
in my apsx page is first the link to jQuery source, then second the JavaScript for the openWindow function:
<script src="../js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
function openWindow(url) {
var w = window.open(url, '', 'width=1000,height=1000,toolbar=0,status=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1');
w.focus();
}
</script>
and the link that makes it all happen:
<asp:LinkButton Text="Open New Window" ID="LnkBtn" OnClick="OpenButton_Click" runat="server" EnableViewState="False" BorderStyle="None"></asp:LinkButton>
Im not a jQuery expert and must attribute some of this to the following blog:
https://blog.yaplex.com/asp-net/open-new-window-from-code-behind-in-asp-net/
i am getting values from .cs to script but i want to send data from script to .cs page
i have tried this,but it is not working.
<script type="text/javascript">
$(document).ready(function() {
$("hfServerValue").val("From ClientSide!");
});
</script>
<asp:HiddenField ID="hfServerValue" runat="server" />
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(hfServerValue.Value.ToString ());
}
You can't directly invoke the Page_Load method from script. There are several ways to send data to server.
Try using an XMLHttpReqest
http://www.jibbering.com/2002/4/httprequest.html
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
If you're using jQuery, you may also try $.ajax(), $.load() etc.
Do remember that unlike a submit action which internally creates a request, you're trying to create the request yourself so you might need to deal with stuff like request headers (content-type, content-length etc.), content etc. So, there's a bit of work to do here even though you're trying to do a simple thing. But once you get it running it comes naturally.
You first need to add a control that get the data from javascript and post them back:
<asp:HiddenField ID="hfServerValue" runat="server" />
Then you place data on that control by getting the cliendID.
$(document).ready(function() { $("<%=hfServerValue.ClientID%>").val("From ClientSide!"); });
And then on post back you get them
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
var YourReturn = hfServerValue.Text;
}
}
This is an answer to a question. Of course ajax is a different way.
Update
Now I see the hidden field, this is also a better way the hidden field. The only error is that you did not use the CliendID !. Also I do not know if you use prototype or jquery or just microsoft.
html code:
<asp:Button runat="server" ID="btnTest" Text="Test" OnClick="btnTest_Click" />
Jquery Code:
$('[id$=btnTest]').click(function(){
$('[id$=btnTest]').attr('disabled', 'true');
});
CodeBehind:
protected void btnTest_Click(object sender, EventArgs e)
{
//here not come.
}
Code Behind btnTest event not work ?
I think that making the button disabled in the click event handler is preventing the postback. Try executing the disabling code after some time:
$('[id$=btnTest]').click(function(){
var button = this;
setTimeout(function() {
$(button).attr('disabled', 'disabled');
}, 100);
});
Try to use jQuery class selector:
Add CssClass="MyButton" to your ASP.NET button;
Use this selector in jQuery
Set disabled="disabled" attribute on click
jQuery:
$('button.MyButton').click(function(){
$(this).attr('disabled', 'disabled');
});
The sample code is using the ends-with selector. There is no mistake in selector.
you just need to change the code like this
$('[id$=btnTest]').click(function () {
$('[id$=btnTest]').attr('disabled', true);
});
I have tested this and works fine without any issues.
I can fix your problems:$(".classButton").prop('disabled','disabled');
and remove disabled: $(".classButton").prop('disabled', '');
Wouldn't you just need to do the following:
btnTest.Enabled = False;
in the code-behind file? This will cause a postback but it should work.
It wouldn't work because the generated HTML id is different than the ASP.NET id.
So btnTest will be rendered as another Id.
A quick dirty way is to to run the page, view the HTML source and locate the button's generated Id and pass it as an arugment in the jQuery function.
A better way is to generate the jQuery function through code behind:
Literal1.Text = "$('[id$=" + btnTest.ClientId + "]').click(function(
{$(this).attr('disabled', 'disabled');});";
Edit:
Also I couldn't help but realize that your OnClick attribute should point to btnTest_Click and not btn_Click
I have a LinkButton that has to postback to perform some logic.
Once it is finished, instead of loading the page back up in the browser, I want to leave it alone and pop open a new window.
So far, the best idea I've had is to put the LinkButton in an UpdatePanel, and have it render some JavaScript out when it reloads, yet I think that is totally hacky. Also, if I recall right, JavaScript within a update panel won't run anyways.
Any other ideas?
Use LinkButton.PostBackUrl to set a different page to POST to, and some client script to get a new window (and the old target restored so that future postbacks work normally). The 2nd page can use PreviousPage to get access to any needed state from the original page.
<script runat="server">
void lnk_Click(object sender, EventArgs e) {
// Do work
}
</script>
<script type="text/javascript">
var oldTarget, oldAction;
function newWindowClick(target) {
var form = document.forms[0];
oldTarget = form.target;
oldAction = form.action;
form.target = target;
window.setTimeout(
"document.forms[0].target=oldTarget;"
+ "document.forms[0].action=oldAction;",
200
);
}
</script>
<asp:LinkButton runat="server" PostBackUrl="Details.aspx" Text="Click Me"
OnClick="lnk_Click"
OnClientClick="newWindowClick('details');" />
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
// Do some server side work
string script = "window.open('http://www.yahoo.com','Yahoo')";
if (!ClientScript.IsClientScriptBlockRegistered("NewWindow"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(),"NewWindow",script, true);
}
}
One thing you could try is to have your LinkButton OnClick event do its processing, then register a Page.ClientScript.RegisterStartupScript with the popup code, which will put some Javascript into the tag to fire off after the page loads. This should launch your new window after the processing completes.
EDIT: Reading your comment, I believe you can still use this approach, have your results stored in a session variable, and then have the popup page pull the results from there.