I thought this would be a simple thing to accomplish but am having some issue. My initial asp.net markup for the server control looks like this:
<ucTextArea:UserControlTextArea ID="taRemarks" runat="server" />
However, in the code behind, I have a conditional statement that checks for user rights in order to enable this text field or not, something like this:
if (CurrentUser.AccountTypeID == 4 || CurrentUser.AccountTypeID == 6)
taRemarks.Attributes.Add("enabled", "");
else
taRemarks.Attributes["disabled"] = "true";
Above are two ways I have tried to accomplish this, but haven't worked when rendered in the browser. How can I disable this server control?
Edit: The UserControlTextArea.ascx is defined below:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UserControlTextArea.ascx.cs" Inherits="stuff....UserControlTextArea" %>
<script type="text/jscript" language="javascript">
$(document).ready(function () {
var counterLabel = $('#<%=lblCounter.ClientID %>');
var textArea = $('#<%=tbTextArea.ClientID %>');
var maxNumber = parseInt('<%=txtMaxCharacters.Value%>');
FieldCounter(textArea, counterLabel, maxNumber);
$(textArea).keyup(function () {
CheckFieldLength($(textArea), maxNumber);
FieldCounter(textArea, $(counterLabel), maxNumber);
});
});
</script>
<div id="OuterContainer" runat="server">
<asp:TextBox ID="tbTextArea" runat="server" TextMode="MultiLine" Width="100%"></asp:TextBox>
<span class="fieldLengthCounter">
characters left:
<asp:Label ID="lblCounter" runat="server"></asp:Label>
</span>
<input type="hidden" runat="server" id="txtMaxCharacters" />
</div>
Your question is unclear, but definitely its a UserControl and not a ASP.Net Textbox. So you can disable the textbox inside your UC like this:-
Approach 1 (Preferred):
Add a public property in your UserControl code-behind:-
public bool DisableMyTextbox
{
set { tbTextArea.Enabled = value; }
}
Then you can simply use this property to disable your textbox in Webform:-
UserControlTextArea.DisableMyTextbox = false; //or true to enable back.
Approach 2:
Find your textbox in UserControl class and then disable it:-
TextBox txt1 = (TextBox)SimpleUserControl1.FindControl("tbTextArea");
txt1.Enabled = false;
Related
In a WebForm I have an input checkbox to which I wanna apply server side action.
For example, when the checkbox is checked, I want to change some label's text.
I have tried to use on client side:
<input id="auto" name="auto" type="checkbox" data-toggle="toggle" data-on="AUTOMAT" data-off="MANUAL" <%= string.IsNullOrEmpty(Request["auto"]) ? string.Empty : "checked" %> />
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<asp:HiddenField ID="customSwitch1Change" runat="server" Value="0" />
<script>
$('#auto').click(function () {
$('#<%=customSwitch1Change.ClientID%>').val("1");
$('#form1').submit();
});
</script>
I have used this and this for the input checkbox.
On the server-side I have tried:
protected void CustomSwitch1Change(string auto)
{
if (string.IsNullOrEmpty(auto))
{
Label3.Text = $"customSwitch1 was not checked.";
}
else
{
Label3.Text = $"customSwitch1 was checked and the check value is {auto}.";
}
}
But what I've tried is not working.
What I'm doing wrong? Or is there another way to do this?
You don't need the HiddenField. If you change the jQuery to the code below it will do a form post on CheckBox change.
<script>
$('#auto').change(function () {
$('#form1').submit();
});
</script>
Then you can simply get the value in code behind with
string auto = Request.Form["auto"];
I have a div that displays loading symbol. I am setting visibility on change of a dropdown box. I want to set its visibility to false in C# after the SelectedIndexChanged method is complete.
Here is the div tag :
<div runat="server" clientidmode="Static" id="loadingImage" class="loadingImage" >
<img class="loadingImg" src="../Images/ajax-loader.gif" />
</div>
Here is the jQuery function :
$(document).ready(function () {
//$('#loadingImage').hide();
var modal = document.getElementById('loadingImage');
modal.style.display = "none";
$("#selectSegment").change(function () {
var modal = document.getElementById('loadingImage');
modal.style.display = "block";
});
});
and this is how i am trying to set the visibility in C#
protected void selectSegment_SelectedIndexChanged(object sender, EventArgs e)
{
ckBLBusinessUnits.Visible = true;
loadingImage.Style["display"] = "none";
}
I tried various ways in C# like set visibility to false etc but nothing worked. Kindly help.
Change this:
loadingImage.Style["display"] = "none";
To this:
loadingImage.Style.Add("display", "none");
You can use hide and show methods to perform that action.
<div runat="server" clientidmode="Static" id="loadingImage" class="loadingImage">
<img class="loadingImg" src="loading.gif" />
</div>
<asp:DropDownList ID="selectSegment" ClientIDMode="Static"
runat="server">
<asp:ListItem Value="0">none</asp:ListItem>
<asp:ListItem Value="1">display</asp:ListItem>
</asp:DropDownList>
JS
$(document).ready(function () {
var modal = document.getElementById('loadingImage');
modal.style.display = "none";
$("#selectSegment").change(function () {
if (this.value === "1") {
$("#loadingImage").show();
} else {
$("#loadingImage").hide();
}
});
});
The div tag was outside of the updatepanel, moving the div inside of the updatepanel resolved the issue.
I have a function in the C# code behind of a Sitecore sublayout that returns a string that looks like this:
public string getProductTitle()
{
Item productItem = itemHelper.GetItemByPath(currentItemPath);
Sitecore.Data.Fields.ImageField imgField = ((Sitecore.Data.Fields.ImageField)productItem.Fields["Logo"]);
if (imgField.Value != "")
{
return "<sc:Image CssClass=\"product-image ng-scope\" Field=\"Logo\" runat=\"server\" />";
}
string productTitle = "";
productTitle = productItem["Produkt Titel"];
return "<div class=\"product-name ng-binding ng-scopen\" ng-if=\"!currentProduct.imageNameHome\">" + productTitle + "</div>";
}
And in the ascx I call this fuction:
<%= getProductTitle() %>
The problem is that in the end this is what I'm getting in HTML at runtime:
"<sc:Image CssClass=\"product-image ng-scope\" Field=\"Logo\" runat=\"server\" >";
The / at the end is missing, which breaks the whole line and no image is shown. The
I also tried this:
string a = WebUtility.HtmlEncode("<sc:Image CssClass=\"product-image ng-scopen\" Field=\"Logo\" runat=\"server\" />");
return WebUtility.HtmlDecode(a);
and this:
return #"<sc:Image CssClass=""product-image ng-scopen"" Field=""Logo"" runat=""server"" />";
With the same result.
Am I missing something here? How can I fix this?
I cannot see this working due to the ASP.NET page life cycle.
Sitecore controls are like normal user controls and they run on the server side - returning them as a string will be too late in the page lifecycle for them to render.
I would place the <sc:Image /> control in the ascx page or use a FieldRenderer object to get the HTML from Sitecore
Sitecore.Web.UI.WebControls.FieldRenderer.Render(myItem, "MyFieldName", "disable-web-editing=true");
You can then use logic to show or hide the Image Field and title control based on you requirements. This assumes you are using the Sitecore Context Item.
Replace the <%= getProductTitle() %> with
<sc:Image runat="server" ID="imgLogo" Field="Logo" />
<asp:Placeholder runat="server" ID="phTitle">
<div class=\"product-name ng-binding ng-scopen\" ng-if=\"!currentProduct.imageNameHome><sc:Text runat="server" ID="title" Field="Produkt Titel"/></div>
</asp:Placeholder>
Then in the code behind Page Load method
var currentItem = Sitecore.Context.Item;
if(string.IsNullOrEmpty(currentItem["Logo"])
{
imgLogo.Visible=False;
}
if(string.IsNullOrEmpty(currentItem["Produkt Titel"])
{
phTitle.Visible=False;
}
More information here:
http://gettingtoknowsitecore.blogspot.co.uk/2010/01/displaying-field-values-using-server.html
Since you have two alternate ways you wish to present your information, I would consider moving your controls and HTML to your markup file (ASCX) and then wrapping the segments in asp:placeholder controls.
<asp:placeholder id="imageTitle" runat="server" Visible="false">
<sc:Image CssClass="product-image ng-scope" Field="Logo" runat="server" />
</asp:placeholder>
<asp:placeholder id="textTitle" runat="server>
<div class="product-name ng-binding ng-scopen" ng-if="!currentProduct.imageNameHome">
<asp:Literal id="productTitleLiteral" runat="server" />
</div>;
</asp:placeholder>
You can then toggle the visibility of the placeholder in your code behind during page load.
public void Page_Load{
Item productItem = itemHelper.GetItemByPath(currentItemPath);
Sitecore.Data.Fields.ImageField imgField = ((Sitecore.Data.Fields.ImageField)productItem.Fields["Logo"]);
if (imgField.Value != "")
{
this.imageTitle.Visible = true;
this.textTitle.Visible = false;
}
else {
this.imageTitle.Visible = false;
this.textTitle.Visible = true;
this.productTitleLiteral.Text = productItem["Produkt Titel"];
}
}
This will allow you to ensure proper encapsulation of business logic versus presentation markup, and will work better with the .NET lifecycle.
I have a project that has me a bit stomped on how to proceed in the manner I would like. On one ASP.net page, I have a form that uses a radio list for the selection options. Also, I have images to the right of the categories, which I would like to change when a particular radio value selection is made.
I have researched how to do this with a regular radio button control, but I cannot seem to get over the hump, as I'm using the ASP RadioList control, and I need guidance on why I cannot get the images to change with the following code:
<script type='text/javascript'>
$(document).ready(function () {
$("input:radio[name=option]").click(function () {
var value = $(this).val();
var image_name;
if (value == 'AMD') {
image_name = "AMD_CPU_1.jpg";
} else {
if (value == 'Intel') {
image_name = "Intel_CPU_2.jpg";
} else {
image_name = "Icon_CPU.jpg";
}
}
});
});
</script>
I'm using J-Query here, and my page doesn't blow up on load - yet when I select a value, the image doesn't change. As for the [name=option]
part of the code, I don't have name="option" in the HTML code source... I have the following:
<tr>
<td><input id="MainContent_CPUBuilderForm1_radCPUType_0" type="radio" name="ctl00$MainContent$CPUBuilderForm1$radCPUType" value="AMD" /><label for="MainContent_CPUBuilderForm1_radCPUType_0">AMD</label></td>
</tr>
Where name="ctl00$MainContent$CPUBuilderForm1$radCPUType" instead.
I've tried to insert this as a replacement for "option", but still no dice. Can someone help to evaluate what I'm doing wrong here? A million thanks! Cheers.
The problem that you're having is that you're not assigning the value of the image URI to the <img> tag. So you'll need to add something to the bottom of your function to make that assignment. Since you don't have that HTML in your question, I'll write my answer with the assumption that you have a tag in your code as such: <img id="changingImage" src="" alt="" />.
So just add this to your Javascript before your function closes out:
$('#changingImage').attr('src', '../Images/' + image_name);
That should get it to change the file for you, thought you may need to change the folder it's in per your configuration.
use this
HTML
<div>
<asp:RadioButtonList ID="RadioButtonTipoUser" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Value="1">Dome</asp:ListItem>
<asp:ListItem Value="amd">Emp</asp:ListItem>
<asp:ListItem Value="intel">intel</asp:ListItem>
</asp:RadioButtonList>
<asp:Image ID="img" runat="server" ImageUrl="~/Desert.jpg" />
</div>
JQUERY
$(document).ready(function () {
$('#RadioButtonTipoUser_1').on('change', function () {
if ($(this).is(':checked')) {
$('#img').attr('src', 'Chrysanthemum.jpg');
}
});
$('#RadioButtonTipoUser_2').on('change', function () {
if ($(this).is(':checked')) {
$('#img').attr('src', 'Desert.jpg');
}
});
});
</script>
Welcome to the wonderful world of ASP.net Web Forms Name/ID Mangling.
Update
Having dertermined that you are using an asp.net image tag. Note that you don't have to use an asp.net control for an image you could use a plain old HTML contol with an ID instead; this ID wouldn't get mangled. However I'll stick to the asp.net image control for now.
This requires your script to be on the page and not in a js file.
.aspx
<asp:RadioBUttonList ID="yourID" runat="server" />
<asp:Image ID="Image6" runat="server" ImageUrl="~/Images/Icon_CPU.jpg" />
javascript
$(document).ready(function () {
$("#<%= yourID.ClientID %> input").click(function () {
var value = $(this).val();
var image_name;
var image_path = "/Images/";
//If the images directory isn't at the website root you could use asp.nets
//resolveURL method instead
if (value == 'AMD') {
image_name = "AMD_CPU_1.jpg";
} else {
if (value == 'Intel') {
image_name = "Intel_CPU_2.jpg";
} else {
image_name = "Icon_CPU.jpg";
}
}
//console.log(image_name);
$("#<%= Image6.ClientID %>").attr('src', image_path + image_name);
});
});
The <% %> is a server code block and should be used sparingly in aspx pages. <%= %> is short hand for `<% Response.Write() %>. If you view the source code of the page you will see the ASP.net client ID of the Radio Button List & image controls in the jQuery selectors.
You should also use a tool like FireBug for Firefox or Chrome developer tools to check the paths for the image once you click the check boxes if you are getting unexpected results. Also note the line //console.log(image_name);. Removing comments form this line will dump the value of image_name to the console, which is useful for debugging. See more info here: http://blogs.msdn.com/b/cdndevs/archive/2011/05/26/console-log-say-goodbye-to-javascript-alerts-for-debugging.aspx
Previous Code below - Doesn't address updating the image
A hacky solution is to surround you radio button list with a div or better still a fieldset and give it an id:
<div id="listContainer">
<asp:RadioButtonList ID="yourID" runat="server" />
<div>
Now update your javascript to
$(document).ready(function () {
$("#listContainer input").click(function () {
var value = $(this).val();
var image_name;
if (value == 'AMD') {
image_name = "AMD_CPU_1.jpg";
} else {
if (value == 'Intel') {
image_name = "Intel_CPU_2.jpg";
} else {
image_name = "Icon_CPU.jpg";
}
}
});
});
so I am using javascript to validate an address field simply to pull the zip code off the end.
I have two asp:Labels that I show and hide to inform the user. It works great, the labels show when needed and the validation works how I want it, the problem comse when I try to hide them. One of the labels shows and hides just fine, but whenever I try to hide the other the script breaks
<script>
function isvalid()
{
var zip = MainContent_tbx_Appt_Address.value.slice(-5);
if (zip == "") {
MainContent_lbl_Add_validate2.hidden = true;
MainContent_lbl_Add_Validate.hidden = false;
}
else if (!zip.match('[0-9]{5}')) {
//MainContent_lbl_Add_validate.hidden = true;
MainContent_lbl_Add_validate2.hidden = false;
}
else
{
//MainContent_lbl_Add_validate.hidden = true;
MainContent_lbl_Add_validate2.hidden = true;
}
}
</script>
<asp:Label ID="lbl_Add_Validate" style="z-index:100;" Name="lbl_Add_Validate" DataPoint="dp_Add_Validate" runat="server" hidden="true" Text="Address is required"></asp:Label>
<asp:Label ID="lbl_Add_validate2" style="z-index:100;" Name="lbl_Add_Validate2" DataPoint="dp_Add_Validate2" runat="server" hidden="true" Text="Invalid address format"></asp:Label>
<br />
<asp:TextBox ID="tbx_Appt_Address" onblur="isvalid()" style="z-index:100;" Name="tbx_Appt_Address" DataPoint="dp_Appt_Address" runat="server" Rows="4" TextMode="MultiLine" Height="65px" Width="200px" value="Address" onFocus="if (this.value == this.defaultValue) { this.value = ''; }" placeholder="Address">Address</asp:TextBox>
this is my code in my asp file and when it hits the client side it spits out this
<span id="MainContent_lbl_Add_Validate" name="lbl_Add_Validate" datapoint="dp_Add_Validate" hidden="true" style="z-index:100;">Address is required</span>
<span id="MainContent_lbl_Add_validate2" name="lbl_Add_Validate2" datapoint="dp_Add_Validate2" hidden="true" style="z-index:100;">Invalid address format</span>
<br/>
<textarea name="ctl00$MainContent$tbx_Appt_Address" rows="4" cols="20" id="MainContent_tbx_Appt_Address" datapoint="dp_Appt_Address" value="Address" onfocus="if (this.value == this.defaultValue) { this.value = ''; }" placeholder="Address" onblur="return isvalid()" style="height:65px;width:200px;z-index:100;">Address</textarea>
everything else works as long as I have MainContent_lbl_Add_validate.hidden = true; commented out, but if I have ether of them run it breaks
In aspx pages if you are not using jQuery, try to get elements using document.getElementById('MainContent_tbx_Appt_Address'), and if you are using microsoft ajax frameworks you can use $get('MainContent_lbl_Add_validate'), these are the right ways to refer elements on DOM.
Editing: ok, looking your code with more accuracy I saw that you made a mistake on span ids, specifically at 'V' char. Check the case on ids and your script will run.
If you hide an element that has "runat=server", you might think that ASP will render the control styled so that it is invisible-- meaning you can later unhide it using Javascript. That's not how it work. If you set hidden=true, the element isn't rendered at all. Your Javascript is gagging on the reference to the missing element and halting execution, so your valiator code doesn't ever get a chance to run.
To render a hidden element, mark it up like this:
<asp:Label ID="lbl_Add_Validate" style="z-index:100;" Name="lbl_Add_Validate" DataPoint="dp_Add_Validate" runat="server" style="visibility: hidden" Text="Address is required"></asp:Label>
Personally I would let JQuery handle this, which you can do in .aspx:
$(function () {
$('#tbx_Appt_Address').blur(function(){
var text_input = $('tbx_Appt_Address').val();
//additional logic with conditions
if (text_input=='')
{
$('lbl_Add_Validate').show();
}
//etc etc
});
});