Convert HTML table code to asp:table control - c#

I have an HTML table code (starts with <table> and ends with </table>), how can I make my asp web page to add this table programmatically?

If you have purely HTML code generated in server side, then you can add that HTML code having <Table> into your asp page like this.
Add a placeholder to aspx page like this.
<asp:PlaceHolder ID="plc" runat="server" />
In page_load event write this.
String str = "<table><tr><td>TD VALUE</td></tr></table>";
plc.Controls.Add(new LiteralControl(str));
This will emit html code , and place them to placeholder.
ASSUMPTION This is just a readonly html code , that you wan to show in page, you are not intended to get those value in server side code on post back. Nor there is any editable field inside the generated table.

if you want to access this table programatically then use
<table runat="server" id="YOUR_ID"></TABLE>
it will then let you access this control through asp.net

Either redo it in asp:table as you already mentioned or add runat="server" to your existing table and you will be able to alter it in codebehind.
After runat = server you can do things like
protected void Page_Load(object sender, EventArgs e)
{
var str= tbl1.Rows[0].Cells[2].InnerHtml;
}
But I would probably redo it in <asp:table> if you are using webforms. See full example here
Add rows to a table dynamically

Related

Adding a ASP Control to page from Code Behind within InnerHTML

I'm trying to add a button to the webpage, from the code behind. I have a single empty div on my main page that visible on and off, when needed. However the content I wish to create dynamically as the div content can change dependent on conditions.
I have realised that within my ASP Control I use a / (backslash) which cancels out my HTML. The problem I now have is understanding how I can get around this with code, is there a way to add ASP Controls to the web page? I am open to suggestions outside of the InnerHtml.
I'm creating my Button like so (in my Code Behind):
string buttonout = string.Format("<asp:Button ID=\"helpButton_0\" CommandArgument=\"0\" CssClass=\"HelpButton\" runat=\"server\" Text=\"?\"/>");
innercontent[0] = string.Format("<table><tr><td>Lead Passenger Information</td></tr><tr><td>Here by deafaul we used your detaisl from your profile, if you're not the lead passenger (As in you're booking for someone else) then please change details.</td></tr><tr><td>{0}</td></tr></table>"+ buttonout);
As Said above, The reason this doesn't work is because of InnerHtml hating backslashes, I think.
I do have a solution to this; and that's by adding more divs to the page.
<div id="HelpBoxDiv" runat="server" Visible="false">
<div id="HelpBoxDiv_Top" runat="server" Visible="true">
</div>
<div id="HelpBoxDiv_Bottom" runat="server" Visible="true">
<asp:Button ID="button_HelpBox_false" runat="server" />
</div>
</div>
I would then add my Innerhtml to the _Top Div, instead of the HelpBoxDiv which I am currently doing now. However this solution doesn't teach me anything.
I am hesitant to ask questions here, as I know a lot of question have been asked and I am sure this one has before, but I didn't find a solution. Any help is much appreciated.
Thank you.
I have realised that within my ASP Control I use a / (backslash) which
cancels out my HTML. The problem I now have is understanding how I can
get around this with code, is there a way to add ASP Controls to the
web page? I am open to suggestions outside of the InnerHtml.
You cannot add ASP.Net server control like a literal string.
Instead, you want to add the dynamic server control to the following approach -
ASPX
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
Code Behind
protected void Page_Init(object sender, EventArgs e)
{
var button = new Button
{
ID = "helpButton_0",
CommandArgument = "0",
CssClass = "HelpButton",
Text = "?"
};
button.Command += button_Command;
PlaceHolder1.Controls.Add(button);
}
private void button_Command(object sender, CommandEventArgs e)
{
// Handle dynamic button's command event.
}

ajaxfileupload multiple inputs on page

I'm using ajaxFileUpload as described here: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AjaxFileUpload/AjaxFileUpload.aspx
It is working fine except when I have multiple file upload controls on the same page. Specifically, I am trying to upload different files for different questions. When I upload the first on the page, it works fine, but the one lower down on the page will only upload it's file into the answer for the first question.
I'm not sure that makes sense... so it may help you to know that my page is populated with questions dynamically using ascx files. The document ascx file looks like this:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Document.ascx.cs" Inherits="ScholarshipApplication.controls.questions.Document" %>
<ajaxToolkit:AjaxFileUpload OnUploadComplete="UploadComplete" ID="FileUploadControl" MaximumNumberOfFiles="1" runat="server" AllowedFileTypes="png,jpg,jpeg,pdf,tiff,tif,gif" />
<asp:LinkButton ID="downloadButton" runat="server" CausesValidation="false" OnClick="downloadButton_Click" />
And the code behind:
public void UploadComplete(object sender, AjaxFileUploadEventArgs e)
{
entry.data = e.FileName;
entry.setDocumentData(e.GetContents());
this.downloadButton.Text = e.FileName;
}
My initial thoughts are that somehow I need to help the control's generated javascript to know which question it should be triggering when.
I believe this is a bug in control or this was implemented by some non-obvious reason. Actually, this control doesn't support multiple instances on a page. Consider to use AsyncFileUpload control instead or customize a bit sources of the AjaxFileUpload control. If you prefer second option then you need to download sources from here: http://ajaxcontroltoolkit.codeplex.com/SourceControl/BrowseLatest and change AjaxFileUpload.cs file (here is a path: /Server/AjaxControlToolkit/AjaxFileUpload/AjaxFileUpload.cs). What you need to do is to change ContextKey constant to property for combining context key guid with unique id of control:
public class AjaxFileUpload : ScriptControlBase
{
private const string ContextKeySuffix = "{DA8BEDC8-B952-4d5d-8CC2-59FE922E2923}";
private string ContextKey
{
get { return this.UniqueID + "_" + ContextKeySuffix; }
}
Actually, if you'll look on PreRender method of AjaxFileUpload class you'll easy realize reson for such behavior of this control (the first control handle uploads from all sibling controls on a page).
as per my understanding You need a hidden field variable to identify your question id IN UserControl:
<input type="hidden" id="hdnQuestionId" runat="server"/>
while populating/generating question you need to set this variable , and when you upload the doc , fetch this hidden value and use it.
I created a data attribute named "data-upload-type" on ALL AjaxFileUpload controls and set it to the name of the type. Then I set up the client call to grab that value and set a cookie with the same value. The cookie IS received on the server side functions and I branch based on the value I receive.
Here is an example:
function StartUpload(sender, args) {
var t = $(sender._element).attr('data-upload-type');
document.cookie = 'upload-type=' + $(sender._element).attr('data-upload-type') + ';';
}
<asp:AjaxFileUpload ID="afuUploader1" runat="server" OnClientUploadStart="StartUpload" OnUploadComplete="UploadComplete" OnClientUploadComplete="UploadComplete" data-upload-type="UploadType2"></asp:AjaxFileUpload>
Then in your server side upload call simply check Response.Cookies("upload-type").
Works like a charm!

Add html layout to a blank aspx page

Want to create dynamic html layout without any asp controls. Actually I want to leave on aspx page only the first line
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Kletka._Default" %>
and the generate full html layout on codebehind. Advise pls how to implement this.
One way is this:
protected void Page_Load(object sender, EventArgs e)
{
string coolHTML = #"<div class=""someclass"">... and other cool content</div>";
Response.Write(coolHTML);
}
With that said. This is a terrible idea. Constructing HTML dynamically on code behind is a nightmare to maintain, it doesn't perform as best as it can and you lose many other features that asp.net offers, which are the main reason to use ASP.NET in the first place.
What you can do is create User controls for specific things (footer, header, left panel, etc) and define a layout for them in markup; then on Code behind, you can add them to specific place holders in the page, depending on some business conditions.
Assuming you have a master page (or at least some content place holders in the page) as so:
<asp:ContentPlaceHolder id="footer" runat="Server" />
On code behind you can do:
footer.Controls.Add(new FooterControl());
Update OP just mentioned in the comments that he doesn't like asp.net controls...
You don't have to use ASP.NET controls, you can use regular HTML controls and set their runat="server" attribute if you need to be able to manipulate their properties on server-side. For example:
<div id="mydiv" runat="server" > some content </div>
On Code behind:
myDiv.Attributes.Add("class","css_class");
myDiv.Attributes.Add("onclick","callJavascriptFunction();");
// and so on.
It's okay to do this sort of thing occasionally under very specific circumstances but I'd avoid this sort of code because is difficult to maintain. Imagine you need to add another class to the myDiv element, for example. Now, you'd have to change you code as opposed to just changing your markup...
So...you want to use ASP.NET web forms without using the built in controls like GridView and so on, at all?
You can write your html and use protected properties?
<%= SomeWhereText %?
or to have the FULL html layout in the code behind make a property
protected string MyEntirePage {get;set;}
and build the string in the code behind
MyEntirePage="<h1>Hello</h1><p>body here</p><p>the end</p>";
and write it out in the aspx page via
<%=MyEntirePage%>
Re: "I've got your point, but I really don't like asp.net controls. I'd prefer to use html controls and customize them with js"
Install NancyFx or maybe the old (but still great) WCF Web Api and use something like KnockoutJs, jQuery or Backbone to perform ajax calls for the dynamic content = no asp.net web forms at all. Yay.
You would need to dynamically add the controls in the Page_Init event. So you need a container to hold your HTML, so you should start by adding a Panel to the Page, then the page's controls would get added to the Panel.
Panel pnl = new Panel();
Page.Controls.Add(pnl);
TextBox txt = new TextBox();
pnl.Controls.Add(txt);
etc....

how to access repeater label value in javascript

This is my javascript
function btnEditClick() {
alert(document.getElementById('<%=LblRefPhyID.ClientID %>').value);
}
<asp:Repeater ID="repeaterRefPhysicianList" runat="server">
<ItemTemplate>
<tr onclick="selectRow(this);">
<td class="csstablelisttd" style="display: none;">
<asp:Label ID="LblRefPhyID" runat="server" Text='<%#Eval("Ref_Phy_ID")%>'></asp:Label>
</td>
on clientclick of Edit button i have to pass RefphyId to another page how can i do that..
It's a repeater. That means that the ItemTemplate will be repeated for each item in your databound collection.
This comes with a caveat: IDs are supposed to be unique. So when you say that your asp:Label has an ID of LblRefPhyID, ASP.NET automagically does you the favor of generating unique IDs for each instance of the repeater that eventually makes its way to your generated HTML. These generated IDs will be based on your original value of LblRefPhyID, but it won't be exactly that, so a plain document.getElementById() outside of the repeater won't work.
There are many ways to work around this, and the very first step you need to do is to actually write some code that will take the automatic generated IDs into account. Maybe write some Javascript to cache the IDs using LblRefPhyID.ClientID, maybe do it dynamically onclick, whatever.
EDIT
And, oh yeah, #Pointy is completely correct in stating that label elements don't have values, just their inner HTMLs. I don't get why he got downvoted for giving a correct response.
Try to set css class instead of id and bind elements click event by class name.
I'm using jquery for this:
$(document).ready(function(){
//bind click event on our label class
$('.lblRef').live('click', function(){
alert($(this).text());
});
});
And this in asp.net page code:
<asp:Label CssClass="lblRef" runat="server" Text='<%#Eval("Ref_Phy_ID")%>'></asp:Label>
HTML <label> elements don't have a "value". They do have contents:
alert(document.getElementById('<%=LblRefPhyID.ClientID %>').innerHTML);
Best way would be to check what is the pattern of id generated by the repeater on the client side and then you can use that id to get the value of the label using innerHTML.
For instance in your case id generated may be :
repeaterRefPhysicianList_LblRefPhyID_01 to till the number of rows in source.
So you can use this information with innerHTML to get the value of the label..
All in all just check your html page you will know what to do next :)

ASP.NET Expression: Accessing the Property of a Class

Is there any way to directly access a field of class in the aspx page?
I have tried this:
In the aspx page I have added:
<form id="LoginForm" runat="server">
<asp:Label Text='<%# Eval("Test") %>' runat="server" ID="jym" />
</form>
and in the backend class of this page I have declared a property as:
private string test;
public string Test {
get {
return test;
}
set {
test = value;
}
}
This property is initialized in Page_Load() as: Test = "JYM";
But the problem is I am unable to see this value in the browser. The tag is rendered into <span/> but without any content.
What I am doing wrong?
Are you calling Page.DataBind() in Page_Load()?
You are using the # data binding operator in your embedded code block. The values that you bind to the control will only show after you have called DataBind() from either the control or the page (which will in turn call it for each control on the page).
If you only want to bind a value to that single label control you could just call jym.DataBind().
I would however suggest using a more descriptive name (id) for the Label control so it is clearer in the code about what is being databound.
See this page for more details.
UPDATE (extra info requested by OP in comment)
So you have 3 options:
1.
Call DataBind() as suggested above.
2.
Don't use a server side control for the label. Just use plain HTML and then you can use the following syntax:
<p><%= Test %></p>
3.
Set the value of the label in the code behind. For example in your page load you might have the following:
protected void Page_Load(object sender, EventArgs e)
{
jym.Text = Test;
}
You may want to use <%= this.Test%>. You can also do this.jym.Text=Test; in the Page Load evt.

Categories

Resources