Access div element from code - c#

I have a div element which I would like to change it'e dir attribute from the code.
The problem is that I can't set the runat=server attribute on the div, so it's not accessible from the code.
Using asp.net, c#, framework 4.0.
Any idea?
Thanks.

If you don't want to set the div to runat="server" so you can do the following:
<div dir='<%= GetDir() %>'>
Your text
</div>
and in the code behind you can set the direction using the following code:
if(You Condition)
{
return "ltr";
}
else
{
return "rtl";
}

Yes, you can't access to the client elements on the page, only to the server-ones (asp.net is a server-oriented framework). The client controls are compiled to the Literal controls with html in them.
If you don't want to set div for the runat="server" attribute, you can register client script to edit your divs content.
If you set the runat="server" attribute, and set the ID="YOUR_DIV_ID_HERE" for it, it will be accessible from code under YOUR_DIV_ID_HERE name.

If you want you can do this also
<div><%= your server variable %> </div>

Use Jquery and call back function to call server side function.

You can set the runat="server" attribute on a HTML element. Just did a local demo, works just fine. It will be represented as an HtmlGenericControl (http://msdn.microsoft.com/en-us/library/7512d0d0(v=VS.100).aspx).
EDIT: You say you cannot use runat="server" to access the element from code. I am not sure why that would be a problem, as the html rendering should be no different. Maybe it has to do with the elements client side id beeing changed? If you depend on this, you could try setting ClientIdMode=Static for your div.

Related

How do I toggle twitter bootstrap as validation in web form?

I know I can place any value from my code behind virtually anywhere on my aspx by using:
<%=myString%>
I also know that in order for me to make a field required using twitter bootstrap I need to use required before my tag closes as in:
<asp:TextBox ID="txtFName" runat="server" CssClass="standard_tb" required/>
In my project I want to be able to set that variable to required or null.
When I try using the method above I get the The server tag is not well formed if i use <%#myString%> within my label or I get the error Server tags cannot contain <% ... %> constructs if I use <%=myString%>
How do I get around this?
As you've seen you cannot add <% %> tags to a .NET server control.
What you need to do is in the code behind set:
if (someCondition)
txtFName.Attributes.Add("required", null);
else
txtFName.Attributes.Remove("required");
If you need XHTML compliance then instead you'd use the line:
txtFName.Attributes.Add("required", "required");
Which would render as:
<input id="txtFName" class="standard_tb" required="required" />

How to make image visible in C#

I declared an picture in my ASP.NET and set it to hidden by default with style="visbility:hidden;". Is there anyway to access this image from the C# and change its visibility? Here is the img line from the ASP.NET:
<img src="canoe.png" alt="Boat Trailer" height="350px" width="600px" id="canoe" style="float:right; margin-right: 100px; visibility:hidden;" />
Use ASP:Image instead.
<ASP:Image id="myImage" Visibile="False" ImgUrl="link" runat="server">
Then you can access it in the backend with:
myImage.Visible = true;
If it is just server side to control the image visibility, just use,
<asp:Image ID="Image1" runat="server" Visible="false" />
You'll need to make this into a server tag first by adding runat='server' and an id. Then you can change its properties before the page loads like so:
<IMG ID>.Style["visibility"] = "visible";
replacing with the ID of your element.
Note about other answers: C# Visibility property will not change the CSS visibility but will actually remove or add the element, if you simply change that while the element is still set to visibility: hidden then it will still not be visible
Discalimer, this is an untested solution, you may have to check the syntax on the use of the Style property
Option 1
You can change it on the server side by adding an ID attribute and runat='server'.
Option 2
You can use an ASP.NET Image control and apply your changes there.
<asp:Image id="myimg" runat='server'.../>
HOWEVER, if you go with this option, you should still use CSS/Javascript to show/hide your image since setting Visible='false' on a server side control will prevent the HTML from rendering altogether which I doubt is the output your are expecting.
If you are performing this logic on the server side, why do you need to render the image as hidden? If you are showing the image based on user input then you should do it on client side Javascript.

Get clientid in user control from external javascript file

I am developing a user control (ascx) in ASP.NET which uses javascript for manipulating controls. Currently the javascript code is inlined and uses <%= somecontrol.ClientID %> to get the control it needs.
I want to put the javascript file in external file but from external file I cannot use the above syntax for retrieving controls. I have read about possible solutions in this and this answers but the problem is that the user control can be placed multiple times on page. This means that the Controls array (mentioned in the answers) will be rendered several times with different items. As a result the script will not be able to retrieve the id it needs. If I put <%= ClientId %> in the name of array that holds items then I will have the same problem as I am trying to solve.
Any ideas?
Ok, a different approach, that I try to use a JavaScript-class style, and then initialize it for each control.
In the external javascript file, write your code as:
function oNameCls(ControlId1) {
this.ControlId1 = ControlId1;
this.DoYourWork1 = function() {
// use the control id.
// this.ControlId1
}
this.DoYourWork2 = function() {
// use the control id.
// this.ControlId1
}
}
And on the control do the call like that.
<script language="Javascript" type="text/javascript">
// init - create
var <%=this.ClientID%>MyCls = new oNameCls(<%=Control1.ClientID%>);
// do your work
<%=this.ClientID%>MyCls.DoYourWork1();
</script>
Hope now help better.
The way I solve this problem is to use CSS classes or place the controls within containers with known IDs and then traverse into the container's children to get the actual controls. For example:
<asp:TextBox ID="Something" runat="server" CssClass="mycontrol" ... />
Could be accessed via:
jQuery('.mycontrol');
Or:
<div id="ControlContainer">
<asp:TextBox ID="Something" runat="server" ... />
</div>
Could be accessed via:
jQuery("#ControlContainer input[type='text']");
The only real problem with this approach is you're tying your code to specific markup on the page, which can be a hassle if the markup changes a lot.
What about a hidden variable:
<input type="hidden" id="ClientId" value="<%=ClientId %>">
Then from your js:
$("#" + $("#ClientID").val())
Or, put the hash in:
<input type="hidden" id="ClientId" value="#<%=ClientId %>">
...
$($("#ClientID").val())
If you want to find a specific control when there could be multiple copies, this can't be done. How would the external javascript know which of the n controls you wanted?
How can rig the behavior up to a class and find the elements relative to the position of the action control, like this:
UserControl:
<div class="myControl">
<asp:Button id="MyButton" runat="server" Text="Click Me" />
<div style="display:none;">Show me!</div>
</div>
If you jQuery was written to be relative like this:
$(".myControl input").click(function() {
$(this).next().slideDown();
});
In this case, it doesn't matter what the specific IDs are, as long as you can navigate the DOM relatively to the controls you need. Even if it's more complex like .closest("div").next().find(".bob").prev()...whatever you need to get there works.

Creating clickable links in runtime of c# aspx webform

I'm creating asp links using response.write in c#, the same HyperLink code works smoothly when inserted directly in the asp code, but when i copy/paste it to the response.write("...") it appears as an unclickable black text.
Am i forgetting something?
<asp:HyperLink ID='HyperLink1' runat='server' NavigateUrl='Exibe.aspx'> CLICK HERE </asp:HyperLink>
this exact code above thrown in the aspx source works greatly
response.write("<asp:HyperLink ID='HyperLink1' runat='server' NavigateUrl='Exibe.aspx'> CLICK HERE </asp:HyperLink>");
and this turns into a black text
You cannot insert an asp:Hyperlink tag directly into the response stream like that, as the hyperlink is actually a control that needs to "render" itself (if you replaced that with a normal "a" anchor/hyperlink tag it would work fine).
Instead you need to either create the control and add it to the page programatically, or maybe use a repeater control to render the anchors.
You are trying to do totally different things:
the markup (asp:HyperLink) will be compiled.
the Response.Write("asp:HyperLink") will NOT. It will render text as is, and of course you wont't see any link, in fact you should see the text inside the tag asp:HyperLink (inluding the tag itself in the HTML source).
If you want to create a link dunamically you can do it using code snippets below:
<asp:HyperLink ID='HyperLink1' runat='server' NavigateUrl='<%= GetDynamicUrl() %>'> CLICK HERE </asp:HyperLink>
/// Or plain HTML
<%= GetTheLinkText() %>
If you want to generate a hyperlink dynamically on the server-side like this, you can either use Response.Write with an <a> tag like slugster says, or alternatively consider the ASP:Literal control which renders exactly what you give it even if it contains markup e.g.
In your markup:
<asp:literal runat="server" id="MyLiteral" />
In your code:
string myHTMLFragment;
myHTMLFragment = "Hello. I am a link pointing to StackOverflow";
MyLiteral.Text = myHTMLFragment;

How to edit CSS style of a div using C# in .NET

I'm trying to grab a div's ID in the code behind (C#) and set some css on it. Can I grab it from the DOM or do I have to use some kind of control?
<div id="formSpinner">
<img src="images/spinner.gif" />
<p>Saving...</p>
</div>
Add the runat="server" attribute to it so you have:
<div id="formSpinner" runat="server">
<img src="images/spinner.gif">
<p>Saving...</p>
</div>
That way you can access the class attribute by using:
formSpinner.Attributes["class"] = "classOfYourChoice";
It's also worth mentioning that the asp:Panel control is virtually synonymous (at least as far as rendered markup is concerned) with div, so you could also do:
<asp:Panel id="formSpinner" runat="server">
<img src="images/spinner.gif">
<p>Saving...</p>
</asp:Panel>
Which then enables you to write:
formSpinner.CssClass = "classOfYourChoice";
This gives you more defined access to the property and there are others that may, or may not, be of use to you.
Make sure that your div is set to runat="server", then simply reference it in the code-behind and set the "class" attribute.
<div runat="server" id="formSpinner">
...content...
</div>
Code-behind
formSpinner.Attributes["class"] = "class-name";
This question makes me nervous. It indicates that maybe you don't understand how using server-side code will impact you're page's DOM state.
Whenever you run server-side code the entire page is rebuilt from scratch. This has several implications:
A form is submitted from the client to the web server. This is about the slowest action that a web browser can take, especially in ASP.Net where the form might be padded with extra fields (ie: ViewState). Doing it too often for trivial activities will make your app appear to be sluggish, even if everything else is nice and snappy.
It adds load to your server, in terms of bandwidth (up and down stream) and CPU/memory. Everything involved in rebuilding your page will have to happen again. If there are dynamic controls on the page, don't forget to create them.
Anything you've done to the DOM since the last request is lost, unless you remember to do it again for this request. Your page's DOM is reset.
If you can get away with it, you might want to push this down to javascript and avoid the postback. Perhaps use an XmlHttpRequest() call to trigger any server-side action you need.
Add the runat="server" attribute to the tag, then you can reference it from the codebehind.
Add runat to the element in the markup
<div id="formSpinner" runat="server">
<img src="images/spinner.gif">
<p>Saving...</p>
</div
Then you can get to the control's class attributes by using
formSpinner.Attributes("class")
It will only be a string, but you should be able to edit it.
How do you do this without runat="server"? For example, if you have a
<body runat="server" id="body1">
...and try to update it from within an Updatepanel it will never get updated.
However, if you keep it as an ordinary non-server HTML control you can. Here's the Jquery to update it:
$("#body1").addClass('modalBackground');
How do you do this in codebehind though?
If you do not want to make your control runat server in case you need the ID or simply don't want to add it to the viewstate,
<div id="formSpinner" class="<%= _css %>">
</div>
in the back-end:
protected string _css = "modalBackground";
If all you want to do is conditionally show or hide a <div>, then you could declare it as an <asp:panel > (renders to html as a div tag) and set it's .Visible property.
To expand on Peri's post & why we may not want to use viewstate the following code:
style="<%= _myCSS %>"
Protected _myCSS As String = "display: none"
Is the approach to look at if you're using AJAX, it allows for manipulating the display via asp.net back end code rather than jquery/jscript.

Categories