Adding a ASP Control to page from Code Behind within InnerHTML - c#

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.
}

Related

Changing button label from c# code-behind

I am sorry I can't solve what must be simple to everyone else even after reading so many posts. Simply stated... I have an ASP webpage I created in VS2010 and when the user clicks the 'Send Email' button, I want to change the button either using JQuery then calling my code-behind to do the actual send. Alternatively, I want the C# code behind to change the button text while it is in the process of sending so the user knows to hold on.
I am new to JQuery and still pretty new to C#. My website is www. themilwaukeehandcenter.com. If you click the contact us... this is where I want the code. I have tried
$("ContactUsButton").click(function () {
ContactUsLabel.Text = "Processing";
});
on the main page. I have also tried
protected void ContactUsButton_Click(object sender, System.EventArgs e)
{
ContactUsLabel.Text = "Sending... Please Wait";
ContactUsLabel.Refresh();
I know this should be simple but hours later.... reading so many posts later.... I feel no farther. I can't quite figure out how the JQuery onclick and the ASP onclick interact. I also don't know why C# flags the Refresh() as not valid. Any help welcome.
I actually placed a ContactUsLabel on the form too when I couldn't get the ContactUsButton to do what I intended. I am too knew to understand what you mean by 'How have you declared your button, but this is the code that creates it:
<asp:Button ID="ContactUsButton" runat="server"
OnClick="ContactUsButton_Click" Text="Send Email" Width="120px"/>
<asp:Label ID="ContactUsLabel" runat="server" Text="" Width="120px">
</asp:Label>
Your WinForm Code:
<asp:button id="ContactUsButton" runat="server" onclick="ContactUsButton_Click" cssClass="myButton" text="Contact Us" />
On submit use the jQuery script to change button text.
$(document).ready(function() {
$('.myButton').click(function(){
$(this).attr('value', 'Processing...');
});
});
View in fiddler: view
Finally at the server side:
protected void ContactUsButton_Click(object sender, System.EventArgs e)
{
ContactUsButton.Text = "Thank You";
}

AjaxFileUpload inside a Panel not working

Hello I'm having trouble getting the AjaxFileUpload control to work properly. I have it working properly on a different page, using identical code, but not inside of a panel on this page. It functions properly and allows me to select files and hits the 'OnUploadComplete' function, however it is crashing on the .SaveAs giving me NullReferenceException. I put the ghostupload control at the start of the page at the recommendation after finding others with similar problems and this is necessary or the control doesn't work at all.
aspx code (outside panel)
<div style="display:none"> <AjaxControlToolkit:AjaxFileUpload ID="ghostAjaxFileUpload" runat="server" OnUploadComplete="AjaxFileUpload_UploadComplete" /></div>
aspx code (inside panel)
<AjaxControlToolkit:AjaxFileUpload ID="ajaxupload1" runat="server" ThrobberID="loader123" AllowedFileTypes="jpg,jpeg" MaximumNumberOfFiles="2" OnUploadComplete="AjaxFileUpload_UploadComplete" /><asp:Image id="loader123" ImageUrl="images/loading.gif" Style="display:None" runat="server" />
aspx.cs code
protected void AjaxFileUpload_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
//...other logic/file checking (working fine)
ajaxupload1.SaveAs(appSession.GlobalImageFolder + appSession.GlobalProductImageFolder + filename);
}
Been working on this one all day and it's got me stumped! I really like the AjaxFileUpload so I'm hoping I won't have to resort to a different upload control. Really appreciate any help on this one!
Cheers,
Jordan

Find Control in code behind - multiple results controls - nth occurence

I have the following problem.
I have a asp:textbox on the page, runat server with an id of say txt
This text box is in a <div>, nothing special. ie:
<div>
<asp:TextBox id="txt" runat="server"></asp:TextBox>
</div>
The problem is there is some java script which when you push the corresponding button it doubles (copies) the div. This is by design. It is meant to.
When you hit save but at the bottom of the page on a asp:Button, it can't find the value I need because it returns two results.
In the code behind:
(Textbox) blah = (Textbox)senderbutton.FindControl("txt");
string test = blah.text
But the result is essentially--> "The value in the textbox , The value in the textbox"
I.e. it is there twice. I have worked around this by doing the following:
string[] test = blah.text.split(new[] { ',' })
and then only calling the second value in the array or whatever.
BUT, now I have this situation but the problem is that a user can enter a string with a ' , ' in it, hence the splitting goes to crap....
So can I find a control with an id, but only find the nth occurence of it in the code behind?
Seems you need to give different name(like txt0,txt1...) for each copy of the input controls.
You can do this using javascript up on client click(prior to form submission) of your asp button
-- Javascript method
function ModifyName() {
var x = 0;
$("input[name='txt']").each(function () {
$(this).attr("name", $(this).attr("name") + x);
x++;
});
}
-- asp:Button
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClientClick="ModifyName();" onclick="btnSubmit_Click" />
So in code behind you can get the values like this...
protected void btnSubmit_Click(object sender, EventArgs e)
{
var resultArr = Request.Form.AllKeys.Where(x => x.Contains("txt"))
.Select(x => Request.Form[x]).ToArray();
}
Not a very nice solution, but you could examine the Request.Form collection directly upon postback and write some code to process your dynamically added textbox fields.
The best solution would be: avoiding copying the div in js. Since you said "This is by design. It is meant to."(even I really doubt it), there are some alternative solutions:
(1) Don't use the default submit behavior of the form. That is, in the click (js) event of the save button, organize the data in the form and then submit it.
(2) Modify the second(copied) textbox's id so that its id is different from the original one, and then get the data in code behind.
I am not sure why you using FindControl method to find the control when you can directly access the txt control from code behind.
You can get results easily
String test = txt.Text;

Sharepoint Webpart posting data to Application Page via PostBackUrl

I have a Webpart that contains a couple of dropdowns on an update panel. There is a submit button that has the PostBackUrl set to a sharepoint Application Page
<asp:DropDownList ID="ClassSelector" runat="server" Enabled="False"
AutoPostBack="True" onselectedindexchanged="ClassSelector_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-null-">Select Class...</asp:ListItem>
<asp:ListItem Value="1">Class 1</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnSubmit" runat="server" Text="Show Page" Enabled="False"
PostBackUrl="~/_layouts/MyWebParts/MyAppPage.aspx" />
This works in redirecting the browser to the Application Page I have created, but I am having trouble accessing the form data.
On the Page_Load function of the Application Page I have the following debugging code.
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "";
foreach (String s in Page.Request.Form.AllKeys)
{
Label1.Text += s + ": " + Page.Request.Form[s] + "<br />";
}
}
This shows that the data I need has in fact been posted to the page.
ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$SemesterSelector: 28
ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$ClassSelector: 11-0021-A
But when I try to access this as:
Page.Request.Form["ClassSelector"]
Nothing is returned. I know I must be missing something simple here, but I am not sure what.
Any help is greatly appreciated.
Ah, the ASP.NET master page prefix problem! One of my favorites.
The master page for your application page puts a prefix in front of your server-side controls so that they will be unique. If you end up access your control via the Form collection, you have to access it using not only the control ID, but also the ContentPlaceholder prefix. That's why you see such a large ID dumped out of your debugging logic.
If you want to programmatically get to the ID of the control, you can use FindControl, but you'll have to target the apppropriate content placeholder scope for this. Here's a good tutorial/explanation here (which really emphasizes how complex this can get!).
Of course, the other option you can use is just hard-coding the control id based on what you're seeing from your debugging code...but that won't be reliable if you change content placeholders or more your control to a different container.
I guess the answer depends on how static your controls will be.
Hope this helps. Good luck!!
Well to access it that way you would have to use
Page.Request.Form["ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$ClassSelector"]
As you can actually see from your code where you set the label text to s plus Request.Form[s]

ASP.Net Label change in C#

I am usually dealing with c# code , but recently developing a asp.net page , I have a Calendar that Appears and the user selects the date he/she wants. On that page is a asp lbl that i would like to display the currently selected date, which is normally easy for me but i am having trouble referencing/finding the control . Also I am unsure of the best way to do achieve this and i'm sure to come across this problem in the future.
This is where I would like to set the lbl text and have tried using the FindControl method but it's not working for me , thinking its possibly nested as i have some divs?.
public void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
Control Lbl = FindControl("inputField");
if (Lbl != null)
{
//Control mycontrol2 = Lbl.Parent;
Lbl.Text = Calendar1.SelectedDate.ToShortDateString();
}
and this is in asp.
<div id="date">
<input type="text" size="12" id="inputField" />
<script>
$("#inputField").click(function () {
$("#box").show("slow");
});
</script>
</div>
How do I accomplish setting the inputfield text to the Calendar.SelectedDate ?.
(and any tips you have come across yourself if any, for good practice)
Thanks For any help.
Any reason why you're not using an asp:Label? You can't find the "label" because it is an html control, aka a client side control. Use an <asp:Label id="lblCal" runat="server"... and you should have no problem changing its text in code behind:
lblCal.Text = Calendar1.SelectedDate.ToShortDateString();
Asp.Net considers only server tags as being controls available at C# level.
All those DIVs and other tags are just plain text for the Asp.Net, they will no be considered in the control hierachy.
To make Asp.Net consider it in the server, place the runat="server" attribute on the tags of your interest. They will become accessible in the code-behind by the name placed in the id attribute.
Asp.Net will never be abled to find the 'inputField' in your sample code.
Solution:
To solve your problem I recommend you use an Asp.Net WebForm control called TextBox... if what you want is an input:
<asp:TextBox runat="server" id="inputField" />
By doing this, you will be abled to access the inputField, in the code-behind by name:
inputField.Text = Calendar1.SelectedDate.ToShortDateString();

Categories

Resources