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.
Related
I have some user controls in my .NET web application, I'm using them in the same page. They have some properties and for some reason I need some hidden fields that hold the values of the properties.
So in one of the user controls there's this piece of code:
<input type="hidden" data-versus="PL" value="<%= vs_pl %>" />
Where vs_pl is the property of the control:
private decimal? _vs_pl; // plan
public decimal? vs_pl {
get { return _vs_pl; }
set { _vs_pl = value; }
}
All this is rendered correctly as this:
<input type="hidden" data-versus="PL" value="-190.2">
In the other user control I have a similar piece of code:
<asp:HiddenField ID="hfOrg" runat="server" Value='<%= org %>' />
Where org is a property similar to the above one. But this is rendered as:
<input type="hidden" name="ctl00$cs$hfOrg" id="cs_hfOrg" value="<%= org %>">
In the very same page. None of the two controls have data binding or data controls internally and they are not bound to a data source in the page either.
I realize that the first case is not a server control, just a normal HTML input tag, while the latter is rendered by the server. However I find this a strange behavior and I'd expect it to work in the second case too.
Where am I wrong?
<%= %> Is a shortcut for Response.Write and it will only work in plain HTML like here
<input type="hidden" data-versus="PL" value="<%= vs_pl %>" />
You should use DataBindings in server controls like this
<input type="hidden" name="ctl00$cs$hfOrg" id="cs_hfOrg" value="<%# org %>">
It's important to remember that if you use DataBindings you should call the UserControl's DataBind method directly or indirectly but calling the DataBind method of a parent control or the Page itself.
Reference:
https://msdn.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx
https://msdn.microsoft.com/en-us/library/bda9bbfx(v=vs.71).aspx
When you are trying to bind data in a Control you need another syntax.
<asp:HiddenField ID="hfOrg" runat="server" Value='<%# org %>' />
And if that control is outside a Repeater/GridView etc you need to call DataBind() in Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
I have a pretty extensive Classic ASP background (using server-side javascript), and my company is finally (FINALLY) making the push towards recoding everything in ASP.Net (using C#). I have a good grasp on good programming practices in Classic ASP and I usually try to make sure I code things the "right" way. I've been reading ASP.Net tutorials and feel like I have a pretty understanding of the basics. I have good discipline about separating client side javascript into external js files, keeping styling outside of the markup in external css files, etc. So, when reading these novice tutorials I understand the concept of the code-behind pages. It makes sense to me to separate the c# code from what will ultimately become the markup for the page. Making < asp:button > objects and the code-behind rules to alter them makes perfect sense.
However, I'm having a hard time wrapping my head around how to do something simple like I would have done in Classic ASP like this:
<%
if (condition) {
%>
<input type="button" value="click me" onclick="dosomething()" />
<%
}
else {
%>
<span>You don't have permission to see the button</span>
<%
}
%>
I'm having a hard time trying to figure out how I'm supposed to fit the conditional stuff you see above into the code-behind page. If I was showing a button under both circumstances, I'd make an <asp:button> object and style it in the code-behind page accordingly - but in the example above I'm only showing the button if the condition is true, and a span block if false.
I know that you don't HAVE to put ALL the c# code in the code-behind page. I can use the <% %> tags the same way I would do in Classic ASP. But, if I do that then it seems to me that it lessens the relevance of the code-behind page. For example, I know you can use an external css stylesheet to stylize your page and at the same time use inline styles on individual tags as well. I believe this to be poor practice, however. It makes it difficult to later have to adjust the styles on that element if you don't know whether to look in the markup or in the css file to find the relevant styles affecting that element.
It seems to me that the same would hold true for your markup and code-behind pages. Is it just a necessary evil to have to mix the 2, or is there a better way to do what I'm demonstrating above?
You could have in your markup:
<asp:Button .. Visible="False" />
<asp:Label .. Text="You do not have permissions" Visible="False" />
Note the Visible property. ASP.NET web forms is build on the idea of an object model, so the button and label are objects you can work with. In the code behind, you can have:
protected void Page_Load(object sender, EventArgs e) {
.
.
if (Xcondition = true) {
Button1.visible= true;
Label2.Visible = false;
}
else {
Button1.visible= false;
Label2.Visible = true;
}
}
Is the traditional way to accomplish this. You just have to figure out where in the lifecycle you need to do this, as load may not be the best (Init or PreRender event, for instance). If you only need to do this at startup once, do if (!Page.IsPostBack) { .. } to ensure it only runs once.
I made a small example that you can basically just copy/paste and mess around with a little.
This is the aspx code:
< body>
<form id="form1" runat="server">
<div>
<asp:TextBox runat="server" ID="txtCondition"></asp:TextBox>
<asp:Button runat="server" Text="Check condition" ID="btnCheckCondition" OnClick="btnCheckCondition_Click" />
<asp:Button runat="server" Text="Click me" ID="btnSubmit" OnClick="btnSubmit_Click" Visible="false"/>
<asp:Label runat="server" ID="lblMsg"></asp:Label>
</div>
</form>
</body>
this is the code behind: (if you double click on the btnCheckCondition, the click_event method will be automatically generated in your codebehind.
protected void btnCheckCondition_Click(object sender, EventArgs e)
{
if (txtCondition.Text == "Show the button")
{
btnSubmit.Visible = true;
lblMsg.Text = "You are allowed to see the button.";
}
else
{
lblMsg.Text = "You are NOT allowed to see the button.";
}
}
This will basically check the input in the textbox txtCondition. If it is equal to "Show the button", the second button will become visible. If the text is something else, the button will not appear and a label will say that you are not allowed to see the button.
have a label and a button in the page. check the condition from code behind and based on the condition, hide or show the control. you can use visibility attribute of the controls to hide or show them. Also use asp.net controls so that you can access them from code behind.
Unless you have a good reason not to, use the Visible property. (In ASP.NET Web Forms, you're asking for trouble if you change the structure of the component tree dynamically other than using repeater controls.) What I do is:
Page.aspx
<button type='button' Visible='<%# condition %>' runat='server'>
Click Me!
</button>
<span Visible='<%# !condition %>' runat='server'>
No button for you!
</span>
Page.aspx.cs
protected void Page_Load() {
if (!IsPostBack) DataBind(); // evaluates <%# ... %> expressions
}
(My preference is to make controls to "pull" data from code-behind instead of pushing it there, and use anonymous and plain HTML controls over their heavier equivalents when possible.) Any way of setting Visible before the page renders will work though.
First to help you with the easy way, to been able the condition to been recognized you need to define it and make it public on code behind. For example:
<%if (condition) {%>
<input type="button" value="click me" onclick="dosomething()" />
<%}else { %>
<span>You don't have permission to see the button</span>
<% } %>
and on code behind
public partial class OnePage : System.Web.UI.Page
{
public bool condition = false;
protected void Page_Load(object sender, EventArgs e)
{
// here change the condition
}
}
Second case with function call
<%if (fCheckAuth()) {%>
<input type="button" value="click me" onclick="dosomething()" />
<%}else { %>
<span>You don't have permission to see the button</span>
<% } %>
and on code behind
public partial class OnePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public bool fCheckAuth()
{
// return your evaluate
return false;
}
}
More asp.net form style
Now, working with the new asp.net (compared with the classic asp) you can also do that (and similar to that).
<asp:Panel runat="server" ID="pnlShowA">
<input type="button" value="click me" onclick="dosomething()" />
</asp:Panel>
<asp:Panel runat="server" ID="pnlShowB">
<span>You don't have permission to see the button</span>
</asp:Panel>
Use one asp:Panel to warp your full content, and on code behind you open it and close it.
public partial class OnePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (condition)
{
pnlShowA.Visible = true;
pnlShowB.Visible = false;
}
else
{
pnlShowA.Visible = false;
pnlShowB.Visible = true;
}
}
}
While the question is not about using ASP.NET Web Forms versus ASP.Net MVC. I felt compelled to point out that it may be more beneficial going with ASP.NET MVC rather than ASP.NET Web Forms in your scenario.
I say this because Classic ASP and ASP.NET MVC inline style is similar. In most cases you could probably convert ASP (<% %>) to Razor(a different flavor of in-lining server-side code with HTML) with little modification to the underlining logic. I don't know about you but the less code I have to write the better. For example, your above code would convert to the following Razor syntax:
#if (condition) {
<input type="button" value="click me" onclick="dosomething()" />
}
else {
<span>You don't have permission to see the button</span>
}
To answer your question, I would disable the button on the server-side. Have a disabled on the client. In the case the button is disabled, enable the Label with the appropriate text.
//Code-behind
bool correctPermission = true;
submit.Enabled = correctPermission;
noPermissionMessage.Enabled = !correctPermission;
//Client Code
<asp:Button ID="submit" runat="server" Text="Click Me" />
<asp:Label ID="noPermissionMessage" runat="server" Text="You don't have permission to see the button" Enabled="false" />
I want to change the source of the iframe from a listbox. And here is my code.
<iframe id="iframeID" frameborder="0" width="100%" height="300px"></iframe>
<asp:Button ID="btnView" runat="server" Text="Pop Up HTML Preview"
OnClientClick="ShowPopUp();" />
ShowPopUp = function() {
var x = document.getElementById('<%=ListBox1.ClientID %>');
var val = x.options[x.selectedIndex].Value;
document.getElementById("iframeID").src = val;
But error says I have an undefined iframe.
What is wrong?
Please help me. Thanks :)
You may change the source using jquery:
$("#content").attr('src', 'http://your new source here');
so you can invoke this method when the selected item in the listbox is changed.
If it doesn't do anything from C#, make a normal button - ASP tends to add fancy prefixes to its controls' IDs (like ContentPlaceHolder1_btnView), and those can't be accessed that way by .ID from C# code. So you can either chceck these IDs (which are able to change if you move them somewhere else) by browser's source code inspector, or use
<input type="button" ID="btnView" Value="Pop Up HTML Preview"
OnClick="ShowPopUp();" />
(Modify your JS accordingly)
use value, JavaScript is case sensitive
var val = x.options[x.selectedIndex].value;
and change OnClientClick as below
<asp:Button ID="btnView" runat="server" Text="Pop Up HTML Preview"
OnClientClick="ShowPopUp(); return false;" />
Button click event make full post back request to server. So again your Ifram will have default src value after postback. Here you have not given value as default src. So nothing will get after click on button. after you add return false button click will not postback after click.
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');"/>
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.