Access html control from server side - asp.net

How can i access html control from code behind in asp.net. I do not want to use "runat=server" as it is causing problems.
I have made an empty html table and from my code behind, I want to add <td> to it.
Please help.
Thanks,
Prachi

This is not possible without runat="server".
You say this was causing problems. Please say what problems it was causing.
You say you were accessing the table using getElementById? The ID of a server control changes based on what controls it's inside of. You need to get the changed ID to use:
var tab = getElementById("<%= myTable.ClientId %>");
or something to that effect.

You should use runat=server attribute if you want to access it at code behind.
But maybe you can generate some javascript code that adds the td/tr to your table at codebehind. and you can register it yo your page to run at startup.

runat="server"
to the table and the tr elements, there is no way the code behind can access them (as this tells the frame work to expose the elements to the server).
What are you actually trying to do? Have you looked at either DataGrid, GridView or simple Repeater control? These allow you to define a table structure and dynamically add controls to it (usually through data binding, although there are ways to add items to thier ItemCollections).

one way that you could do this is to add some inline scripting and a public string variable. in your code behind, make a public class-level variable:
public String myColumns
then in your Page_Load event, create your HTML as a string and save it in your myColumns variable:
protected void Page_Load() {
//do stuff
myColumns = someStringWithTDTagsInIt
}
Then in your .aspx page, do the following:
<table id=maintable"><tr><%=myColumns %></tr></table>
It should render your HTML as you wanted it to in your Page_Load event (or whatever event you want, if you want it to load on a button click or something) without using a "runat=server" tag.
Please note that this is not the recommended way to achieve this (controls are typically more efficient) but this should be a valid solution to the question you posed.

simple example.
just you place the runat="server" then you can access .
html controls are cannot access at server side. if you place runat server then it access in the server.

Related

What control to render dynamic HTML text on an aspx page

Page_Load generates a string of HTML for a dashboard. (html)
What control on an aspx page to bind that "text" to so when the page renders you see the tables, and buttons within?
Tried
With dhtml.Text = html but I don't see the buttons. I do see the tables as well as the borders of cells that I expect.
Any ideas?
TIA
You can inject any text/html into your ASPX page using: <% =GetMyText() %> where "GetMyText()" is a public or protected method in your code behind that returns a string.
You can also drop a Literal control onto a form and set the text via its "Text" property.
But if you want to do things the ASP.NET way, you might use a Gridview or Repeater to display tabular/repeating data, and Databind to it with some data.
If you are starting out with ASP.NET, you would probably be better off learning ASP.NET MVC as it is easier to get your head around if you are used to writing HTML. ASP.NET Web Forms, which you are using, generally tries to insulate you from HTML, CSS, and Javascript by giving you controls that you drop onto the page and bind data to. The controls do a lot of work for you, but take away almost all control of your HTML, CSS and Javascript.
I use javascript to dynamically create html elements. Your page_load function could register a javascript function which creates the elements you need.
Not sure why you were downvoted, but a very simple one to use is the HtmlGenericControl.
Basically, just add a span or div to your .aspx file and give it an ID and the runat="server" attribute.
Then, in your code behind just set the InnerHtml property of that control to your generated html.

Accessing app setting from aspx and add concatenated text

I've got a project where I'm tasked with changing hard-coded domain references from one domain to another in a group of legacy C#/VB web projects. I want to parameterize the domains as much as possible instead of just replacing with a different hard-coded value. The problem is that there are over 800 of these references in about 30 different solutions, so creating variables in each code-behind to bind to would take forever.
I have added the new domains to the appSettings section of the web.config file, and this works:
<asp:HyperLink Text="Link" NavigateUrl="<%$appSettings:DomainX %>" runat="server" />
But I need to be able to do something like this:
<asp:HyperLink Text="Link" NavigateUrl="<%$appSettings:DomainX %>/newPage.aspx" runat="server" />
But when I add the "/newPage.aspx" the page doesn't compile anymore. I don't really care if this is done with an asp:HyperLink tag or just a tag.
Any ideas on how I can accomplish this?
Thanks.
I think you have two options. The easiest is to just use a plain old anchor tag, if you're not doing anything with the HyperLink server side:
Link
Alternatively, you could set the NavigateUrl in the Page_Load, since <%= will not work properly within the HyperLink server tag:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
link1.NavigateUrl = string.Concat("http://",
ConfigurationManager.AppSettings["DomainX"], "/newPage.aspx");
}
You could also see if you can make a custom binding, something like $myBinding:DomainX, but I don't know if that's possible off the top of my head (I would assume it is though).
EDIT
That $appSettings:DomainX code is called an ASP.NET Expression, and can you can create custom expressions. This post from Phil Haack covers how to set them up, in case you are interested.
How about something along the lines of:
<%=ConfigurationManager.AppSettings["DomainX"].ToString() + "/newPage.aspx" %>
I would go with one of two different approaches that would save you the need to change the NavigateUrl in the .aspx itself.
One option is to inherit from HyperLink class and overriding the NavigateUrl property, adding the ConfigurationManager.AppSettings["DomainX"] in the getter method. Having this, just change <asp:HyperLink ... to <UC:MyLink ...
Second option is adding small function to each page (can be in one shared place and just called from each page) that will iterate over all the hyperlinks controls and dynamically add the domain. To find all controls of certain type you can use such code for example.

Assign database value to hyperlink but not a runat=server

Its simple if I have an ASP.net page with an ASP.net linkbutton / hyperlink
and I obtain a value from say a SQL Database and I store it in the label...
For example:
this.myLabel.Text = someValueReturnedFromADatabase
This is simple because it goes right to the code behind page and set the text value
to the value returned from my database (aside from going into more details with data access layer, etc).
What I was wondering is what if I dont want to use an ASP.net linkbutton and I simply want to use an HTML link button (as I need to call the jquery fade function). How would I set the value someValueReturnedFromADatabase to a control that is not runat=server?
Have a variable in your codebehind:
protected string TextForLabel
Set it in Page_Load, or wherever:
TextForLabel = someValueReturnedFromADatabase;
Reference it with pointy-bracket percent notation:
<% =TextForLabel %>
You can set runat="server" on standard html controls. I do it all the time. Then you will be able to access their properties in your code behind just like you do for asp controls.
If I am not mistaken, for labels you can use .InnerText or .InnerHTML to change the text.
From what I know of, you need to make some sort of relation between your HTML document and the code behind to interact with data from a SQL database. Either that or you'll have to make the entire database connection etc. in the HTML header using script type="text/javascript" and script type="text/C#" or whatever language you use to develop.

Access hiddenfield using Jquery

I have a page that's derived from a master page. On this page, I have a hiddenfield ("hfUser"). How can I access this "hfUser" control and get/set its value using JQuery?
I've tried variants of this:
$(document).ready(function() {
var test = $("#hfUser").val();
alert(test);
});
but test = undefined. I'm guessing I've got the selector wrong, but I don't know how to get an asp hiddenfield. Any ideas?
Thanks
If you are using Asp.net controls, the server will mangle the control ids. It adds a bunch of extraneous control tree hierarchy information into the id. You need to reference what that acutal id is that's getting rendered, which is availble with the ClientID property on the control (hfUser.ClientID) or access your control in a different, more roundabout way, like find the controls parent, then search through its children to find your control.
If you don't have to use the asp.net HiddenField control, try just using a regular old html input.
ASP does like to mangle ID's. The further down the rabbit hole (or nesting controls) you go, the more ASP adds to your control ID. Throw in Master Pages, and it's yet another level or two.
Another way to access server-side controls (with the runat property set), is to use the square brackets in your jQuery selector.
Like this:
$("[id$='hidImgSource']").val()
That selects any elements whose ID has 'hidImgSource' as ending part of the name. So it will find mangled ID's.
Here is a link to the jQuery Selectors page that explains some more options.
If the hidden field is an ASP.NET control, check out this blog post to help you with jQuery selectors for ASP.NET controls
http://www.foliotek.com/devblog/extending-jquery-to-select-asp-controls/
Do it like this:
$(document).ready(function()
{
var test = $("**#<%= hfUser.ClientID %>**").val();
alert(test);
});

ASP.NET: Bind Repeater using jQuery?

I have a Repeater control that I bind server-side. It repeats a series of divs, and does so with no problem. I have some buttons that I use to sort the repeater (newest, highest ranked, random) and this works the way it should.
I would like to improve my user experience by making the buttons sort the divs using Ajax/jQuery somehow so that there is no page postback and the user does not lose his/her spot on the page.
Is there a way to use jQuery to access server-side code like this, or use Ajax to re-bind a server-side control?
Thanks... if I need to list more details, please let me know!
EDIT I'm aware of UpdatePanels, but I would prefer not to use them if I don't have to.
Have you considered moving the Repeater's functionality to the client-side?
Doing it that way, functionality like paging and sorting is not very difficult to add. In fact, you can lean on the framework pretty heavily by using ADO.NET data services as the service layer.
It's relatively easy.
Move your repeater to a separate custom control, let's say MyControl. Now repeater in your page becomes uc1:MyControl.
Wrap MyControl into a div:
<div id="mydiv">
<uc1:MyControl ID="MyControl1" runat="server" />
</div>
Create a new page, pgMyControl.aspx, that contains MyControl only.
On your main page, add jQuery handlers to your sort links. Use load method to dynamically replace div contents:
$('#link_sort_random').click(function()
{
$("#mydiv").load("pgMyControl.aspx&sort=random");
}
Use QueryStringParameter in datasource inside MyControl to change order. Or use Request.QueryString in code-behind file.
Using an updatePanel or a jquery Ajax postback are the same thing essentially. Both will ask your code to fetch the new query, then make your control render itself, and then feed the HTML back to the client as a partial page render, and then insert the content in place of the old content in the same DOM location.
It is considerably harder to make JQuery and ASP.NET talk to each other this way due to the nature of web controls and their lifecycle that determines when they render. An updatePanel knows how to call all this, maintain proper viewstate and return the result to the correct location.
In this case, don't make things any harder on yourself, use the updatePanel unless you have some very specific reason not to.
EDIT: If you're having JQuery issues with update panels it is probably due to the fact that new DOM nodes being created. JQuery has the live event to handle this. It will notice when new DOM elements are created and match them against your selector even after the document ready.
Maybe it's an OT, but you can consider to change the way you bind even the client and the server control, using XSLT transformation instead od the classics server controls.
You can find an example here (sorry, it's in italian...).

Resources