I have the following code:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandle);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandle);
function beginRequestHandle(sender, Args) {
//Do something when call begins.
document.getElementById("btn1").style.visibility = "hidden";
document.getElementById("btn2").style.visibility = "hidden";
}
function endRequestHandle(sender, Args) {
if (document.getElementById('<%= hfResultsCount.ClientID %>').value != 0) {
document.getElementById("btn1").style.visibility = "visible";
document.getElementById("btn2").style.visibility = "visible";
}
else {
document.getElementById("results").innerHTML = "<br><b><center><font style='font-family:Haettenschweiler; font-size:xx-large'>No data found, please try again.</b></font></center>";
}
}
</script>
and the code for btn2:
<input type="button" runat="server" name="btn2" id="btn2" value="New Window"
style="visibility:hidden;font-weight:bold;width:200" onclick="window.open('http://microsoft.com');" />
I am using Js to show/hide buttons (needs to be done like this so don't suggest otherwise) and while btn1 is asp:button it always works but for <input type=button> I keep getting this error
Microsoft JScript runtime error: Unable to get value of the property 'style': object is null or undefined
The way to fix that for btn1 was to just add ClientID=Static but how to do that for <input> button? (I do not want to make it asp:button since I need it to not postback)
Everything is in an UpdatePanel with ClientID=Static also.
I know its something to do with the IDs and the master page since it works fine on a page on its own.
If you do not need to access button on server side then you should not put runat="server", This will make your script to find button and it will not generate error.
<input type="button" name="btn2" id="btn2" value="New Window"
style="visibility:hidden;font-weight:bold;width:200" onclick="window.open('http://microsoft.com');" />
OR, If you want to make runat="server" you can access it like this
document.getElementById(<%= btn1.ClientID %>).style.visibility = "visible";
After the page rendering go to view source and check how ID is appearing with master page you may get some idea
It might not be btn directly....master_xxx
This should work :
<input type="button" runat="server" ClientIDMode="Static"
name="btn2" id="btn2" value="New Window"
style="visibility:hidden;font-weight:bold;width:200"
onclick="window.open('http://microsoft.com');"/>
or, if you don't need to access the control in your code behind :
<input type="button" name="btn2" id="btn2" value="New Window"
style="visibility:hidden;font-weight:bold;width:200"
onclick="window.open('http://microsoft.com');"/>
Related
I am using ASP.NET for a web page in order to make some server calls that involve looking up user organization information. Based on that information, we need to either hide or display a div. In the header I have a C# function that definitely runs. I have tried the following lines to hide the div.
divID.Style.Add("display","none");
and
divID.Visible = false;
In the body, I am currently using an asp:Panel that runs at server and contains the id "divID". No matter what I do, I can't get the div to hide (without manually putting the styling in). I tried putting the scripts before and after the body, and it didn't make a difference. Any suggestions on the best way to do this would be appreciated.
EDIT:
Here is the C# initiating code.
<script runat="server" language="C#">
void getUserInfo(Object sender, EventArgs ev){
The rest of the C# code is irrelevant, but the relevant line shown above is definitely being run.
The HTML portion looks something like this.
<asp:Panel runat="server" id="divID" style="width:200px; height:130px; ">
<div style="text-align:center">Test Data</div>
</asp:Panel>
C# code is always compiled and run from the server-side, and so cannot impact the state of a page once rendered unless you use postbacks or callbacks. If you want to change the visible state of a control on the client-side, you will need to use Javascript on the client side (possibly triggered by a button click) to show and hide the control.
As an example, check out the solution at the link below.
https://forums.asp.net/t/1603211.aspx?Show+hide+div+on+button+click+without+postback
<script type="text/javascript">
function ToggleDiv(Flag) {
if (Flag == "first") {
document.getElementById('dvFirstDiv').style.display = 'block';
document.getElementById('dvSecondDiv').style.display = 'none';
}
else {
document.getElementById('dvFirstDiv').style.display = 'none';
document.getElementById('dvSecondDiv').style.display = 'block';
}
}
</script>
<asp:Button ID="btn" runat="server" Text="Show First Div"
OnClientClick="ToggleDiv('first');return false;" />
<asp:Button ID="Button1" runat="server" Text="Show Second Div"
OnClientClick="ToggleDiv('second');return false;" />
<br />
<div id="dvFirstDiv" style="display: none;">
First Div
</div>
<div id="dvSecondDiv" style="display: none;">
Second Div
</div>
In the header I have a C# function that definitely runs.
If you're talking about the HTML page header - no, it definitely not running. C# code is executed only server side.
Based on your post, I'm assuming we're talking WebForms here and yo have a script block in your aspx file. While this is fine, I recommend placing the server-side code into a code behind file.
So all you need to do is to add a handler for the PreRender phase of the page life cycle and place your logic for showing/hiding the div in there.
public void Page_Prerender(object sender, EventArgs e)
{
divID.Visible = false;
' OR
'divID.Style.Add("display","none");
}
Note that setting the Visible property of a WebForms control excludes the control from rendering to the page, whilst setting display: none renders it as HTML but it isn't displayed on the page.
Try in backcode: divID.Controls.clear();
This worked for me.
I have a cancel button in a form:
#using (Html.BeginForm("ConfirmBid","Auction"))
{
some stuff ...
<input type="image" src="../../Content/css/img/btn-submit.png" class="btn-form" />
<input type="image" src="../../Content/css/img/btn-cancel.png" class="btn-form" />
}
The issue is I want this button to go to a particular view when I click on it. How do I do this?
Either you can convert the Cancel button as an anchor tag with #Html.ActionLink helper method and apply a css class which makes the link to looks like a button and then in the controller action for that link, you can return the specific view.
#Html.ActionLink("Cancel","Index","Products",null, new { #class="clsButtonFake"})
or
Use 2 submit buttons in the form. One for real submit and one for the cancel. and in your controller action, check which button called the action method.
You can read more about it here in this answer.
Lot of the answers worked in either of the browsers, chrome or ie but not all.
This worked in all -
<input type="button" value="Cancel" onclick="location.href='#Url.Action("Index","Home")';"/>
This is my button HTML:
<button type="button"
class="btn btn-inverse"
id="cancel"
onclick="window.history.back()">
<i class="icon-remove icon-large"></i>
<br />#Localization.Cancel
</button>
Then to customize the onclick attribute in some views I do this:
<script>
$(document).ready(function ()
{
$("#cancel").
attr("onClick",
"document.location.href='#Html.Raw(Url.Action("Index", "Standard",
new { ManualId = Model.ManualId, ChapterId = Model.ChapterId }))'");
});
</script>
Or a styled submit button:
<input type="submit" value="Save Form" name="Save" class="submit-button btn-form" />
Then Javascript for cancel button:
<input type="button" onclick="document.location.href('Home/Index')" value="Cancel" class="cancel-button btn-form" />
// Note: This avoids any of the validation that may happen in the model that
// normally gets triggered with a submit
So with Shyju's appraoch, you use the built in MVC ActionLink helper. Doing this, you'll need to have any images or icons done through css. However, this is much more cachable, especially if you use base64 strings for your images in css.
I like Adauto's approach because it gives you much more control of the markup. MVC Html Helpers are nice, but they still seem to have their heads in the WebForms mindset of "don't worry about it, we'll take care of it for you".
The one thing I would add is Url.Content.
<img src="#Url.Content("~/Content/css/img/btn-submit.png" class="btn-form" />
It's never really a good idea to make your views have to know the location of content relative to it's location.
<a href="/Auction/[ActionName]">
<input type="image" src="#Url.Content("~/Content/css/img/btn-cancel.png")" class="btn-form" />
</a>
if you want to preserve its look as a button, you could do something like this:
<a href="/Auction/[ActionName]">
<input type="button" value="Cancel">
</a>
where [ActionName] is the name of the action that will return your desired view.
<img src="../../Content/css/img/btn-submit.png" class="btn-form" />
I ended up making a helper so I could reuse the cancel button. I added a js confirm in case people click the cancel button by accident after filling in the form.
#helper FormCancelButton(string cancelUrl)
{
<button type="button" class="btn" onclick="if (confirm('Cancel changes?')) location.href = '#cancelUrl';">Cancel</button>
}
I then call it like so:
#FormCancelButton(Url.Action("Index", "User" ))
If you are really keen you could try and detect the dirty state of the form too and only show the confirm dialog if the form had been changed.
<asp:Button runat="server" class="btn btn-danger"
CausesValidation="false" onclick="Cancel_Click" Text="Cancel"/>
protected void Cancel_Click(object sender, EventArgs e)
{
Response.Redirect("Test.aspx");
}
My html.
<input id="rdb1" type="radio" name="rdbData" checked="checked" />
<input id="rdb2" type="radio" name="rdbData" />
<asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_Click" />
Button is only asp:button but radio buttons are not.First time when page is load rdb1 is selected.But when i click the button btnTest with check rdb2, page is refreshed and select 1st redio button.To prevent this i try jquery like this.
Inside Document.ready:
var btnTest = "<%=btnTest.ClientID %>";
$('#' + btnTest).bind("click", function() {
if ($('#rdb1').attr("checked")) {
$('#rdb2').attr("checked", false);
$('#rdb1').attr("checked", true);
}
else {
$('#rdb1').attr("checked", false);
$('#rdb2').attr("checked", true);
}
});
But its not work.How can we handle this type of situation.Where i am getting wrong.Any idea or any alternative.Thanks.
If that is the request I would suggest you have a hidden field (server side) which will keep the state of which input radio button is selected (use jquery to update the hidden field when user clicks on the radio buttons). Then on postback as the hidden field is set at runat="server" it will maintain its value (viewstate) and you can simply use jquery to set the right radio button as selected. Does that make sense ?
I repeat that the requirement is ABSURD. How are they going to tell you used server-side controls without looking at the code anyway. This is like requiring that you write the code using chopsticks or something.
However just as an exercise I provide the following solution:
<input id="rdb1" type="radio" name="rbdData" value="rbd1" <%= Rdb1Checked %> />
<input id="rdb2" type="radio" name="rbdData" value="rbd2" <%= Rdb2Checked %> />
<asp:Button ID="btnTest" runat="server" Text="Test" onclick="btnTest_Click" />
And the code behind:
protected string Rdb1Checked
{
get
{
if (IsPostBack)
{
if (Request["rbdData"] == "rbd1")
{
return "checked";
}
else
{
return "";
}
}
return "checked";
}
}
protected string Rdb2Checked
{
get
{
if (IsPostBack)
{
if (Request["rbdData"] == "rbd2")
{
return "checked";
}
else
{
return "";
}
}
return "";
}
}
Ask why they have these requirements. Maybe they don't want to see the client IDs in which case you may set the ClientIDMode to Static and avoid auto generated IDs. You can remove them completely by setting them to null, etc. Maybe they don't like what Web Forms renders for Radio buttons in which case using server side inputs would be OK. The requirement on its own simply does not make sense.
Shree
The fact is that client click (added by jQuery) executes before the call to server. If you want to persist the selectin, try using server sided controls:
<input id="rdb1" type="radio" name="rdbData" checked="true" runat="server" />
<input id="rdb2" type="radio" name="rdbData" runat="server" />
<asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_Click" />
Try this if it does work for you.
Hope it helps.
When the "Test" button is clicked, the page posts back to the server, which re-renders all client-side controls just as if the page has been loaded for the first time. Since the entire page is reloaded, jQuery will also "forget" about the state of the controls, so that approach won't work either. The simplest way to prevent this is to ensure the radio buttons run on the server side. For instance:
<asp:RadioButton id="rdb1" Checked="True" GroupName="RadioGroup1" runat="server" />
<asp:RadioButton id="rdb2" GroupName="RadioGroup1" runat="server" />
Hope that helps!
What do you mean? That you have a requirement that does not let you use "servr side controls" or that your IDE does not allow that?
By definition, in ASP.NET all HTML controls inherit from a server control. Simply adding runat="server", you can access that control from codebehind, although it will still render in page as a normal HTML control.
I am having some very strange behaviour in IE with my .Net buttons.
I have a normal HTML button.
<input type="submit" onclick="return Valadation()" value="Save profile" class="btn primary rounded" />
Which then calls some simple JavaScript
if (txbEmail.length == 0) {
$("[id$='txbEmail']").addClass("error");
$("[id$='txbEmail']").focus().select();
showMessage = true;
displayMessage += "Email Address, "
}
else {
$("[id$='txbEmail']").removeClass("error");
}
if (showMessage) {ShowStatus("warning", displayMessage);
return false;
}
else {
var saveButton = $('[id*="butSave"]');
saveButton.focus();
saveButton.click();
}
With the final result clicking a asp.net button
<asp:Button ID="butSave" runat="server" Style="display: none;" onclick="butSave_Click" />
This issue is that Ie just wont ever post the page back? works fine on FF, Chrome, just not IE
If you need the ASP button to perform javascript validation, use the OnClientClick property:
<asp:Button ID="butSave" runat="server" Style="display: none;" onclientclick="return Valadation()" onclick="butSave_Click" />
Simply return false from your Valadation() method to stop the asp button from submitting.
Turns out this is a known issues within jQuery and wont be fixed, but there is a very easy work around.
The script .click() will not work if the button in question has the type="submit" (only in IE wont this work IE7,IE8,IE9 all show this error).
But if you just change the button type to type="button" the .click() event works just fine.
I want to call a c# function from my javascript function.
I have a link button in my ascx (please see the code below). The problem is that if you press enter in firefox is not working however it is working fine in internet explorer.
<li class="clearfix border_top">
<label for="title" class="first_column bold">Search For</label>
<div class="contactUs_details">
<input type="text" id="advanced_txtBox1" name="advanced_txtBox1" class="searchbox" runat="server" style="width:300px;" />
<asp:CheckBox ID="chkSearchBDJ" runat="server" Text="Search BDJ" CssClass="checkboxlistnoborder" />
</div>
</li>
<div class="img_SearchNow">
<asp:LinkButton ID="btnSearchNow" CausesValidation="true" runat="server" OnClick="btnSearchNow_Click"></asp:LinkButton>
</div>
I have linkButton see above on which I have called on c# function on Click, But if you pree some text in above textbox and press "Enter" it should automatically call function "btnSearchNow_Click". It is working fine in IE but not working in Firefox.
A javascript function to click a button...
function clickMyButton() {
var ele = document.getElementById('btnSearchNow');
if ((ele !== null) && (ele != 'undefined')) {
ele.click();
}
}
The wording of your question could use some cleaning up, or some additional information.
If you are looking for pseudo-submit behavior from inside a text box, take a look at this post. Submit Login control button when I hit Enter
You will have to generate the javascript from the server side, since you are using an ASCX and the ID's are not the ones you defined.
You need to have a submit type on the page for it to work properly in firefox.
<input id="mysubmit" runat="server" type="submit" onclick="return false;" style="display: none;" />
Edit: Here's a google cached page that has more information. The original post doesn't seem to be available ATM, but good old google had it.