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();
Related
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.
}
Now that i've been MVCing for quite sometime i decide to pop some classic C# .Net into my 8 track and have gotten the following issue:
I have a TextBox WebControl on my aspx page that in the code behind i want to simply append a LiteralControl after it.
This doesn't work:
TextBoxAge.Controls.Add(new LiteralControl("Invalid Age."));
This works but all the way at the bottom:
TextBoxAge.Controls.Parent.Add(new LiteralControl("Invalid Age."));
Can you help me!?
For example the HTML will show:
<div>
<input name="TextBoxAge" type="text" id="TextBoxAge" class="Age">
Invalid Age.
</div>
This should be purely dynamic and relative to the control at hand.
Solution:
TextBoxAge.Parent.Controls.AddAt(TextBoxAge.Parent.Controls.IndexOf(TextBoxAge),new LiteralControl("<span>Invalid Age.</span>"));
Maybe you can try something like this. (Don't remember if AddAt will replace the control at the specified index )
var textBoxAgeIndex = TextBoxAge.Parent.Controls.IndexOf(TextBoxAge);
TextBoxAge.Parent.Controls.AddAt(textBoxAgeIndex +1, new LiteralControl("Invalid Age."));
Hope this will help
The best way is to use an a PlaceHolder
From MSDN: Use the PlaceHolder control as a container to store server
controls that are dynamically added to the Web page.
PlaceHolder.Controls.Add(new LiteralControl("Invalid Age."));
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!
I imagine this question has been asked before (hasn't every question?), but I am struggling with the language necessary to find my way to a solution, so here are some specifics:
I have a web form for updating a single location, e.g. street address, city, state, etc., which is dealt with by having a static location-update form with various asp:TextBoxes which are referenced in the code-behind using their intellisensed controls, e.g. StreetAddressTextBox.Text.
I would like to update this form to work for multiple locations. In the past when I worked with PHP, this meant writing a lot of inline code wherein I wrapped the form-contents in a for-loop over the collection I was rendering, and then referenced each item with some ID="StreetAddressTextBox_<%=locationId%>"-like schema.
I'm currently in the process of doing it this way in ASP.NET, but inline feels dirty, especially because I have to kick a lot of code-behind paradigms I've established on other pages where the form-content wasn't scaling based on a collection. My gut tells me there should be some way to template out a location and do everything in the code-behind, but I've yet to stumble upon and example that shows me this in practice.
Thanks for any help in advance.
Assuming I understand you correctly it sounds like you should be using a UserControl.
Basically create a UserControl.ascx file (and VS will generate the UserControl.designer.cs and code-behind classes for you). Then put your input fields in there with no special attributes, like so:
(Note that I prefer HtmlControls to WebControls, they give cleaner markup and don't muddy things. I suggest you give them a try):
<%# Control blargh %>
<label for="<%= Street.ClientID %>">Street address</label>
<input type="text" runat="server" id="Street" /> <br />
<label for="<%= City.ClientID %>">Town / City</label>
<input type="text" runat="server" id="City" /> <br />
<!-- etc -->
Note how I'm not messing with the id="" attribute of the input controls. Now just register it in your web.config:
<add tagPrefix="foo" tagName="Address" src="~/Controls/Address.ascx" />
Then in each page that needs an address form (assuming your UserControl is called AddressControl)
<%# Page blargh %>
<p>Enter your address details below:</p>
<foo:Address runat="server" id="Address" />
Then in your page's code-behind you can just do this:
public override void OnLoad(Object sender, EventArgs e) {
if( Page.IsPostBack ) {
Validate();
if( Page.IsValid ) {
// get values from a POST
String street = this.Address.Street.Value;
String city = this.Address.City.Value;
// and so on
}
} else {
// set values if you're retrieving data from a DB or something
this.Address.Street.Value = "123 Fake Street";
this.Address.City.Value = "Frying Pan City";
}
}
Note how I used the "<%= Street.ClientID %>"-thing. ASP.NET will automatically generate the control names and IDs based on the control's parent name (and so on, recursively). So the actual HTML input will be rendered like this:
<label for="Address.Street">Street address</label>
<input type="text" name="Address_Street" id="Address.Street" />
Note this design and practice only applies to WebForms. ASP.NET MVC is completely different again.
You could just use an <asp:PlaceHolder runat="server" id="plcDynamicControls" />.
In your code behind create a private List<WebControl> dynamicControls.
During .Init() return whatever logic is appropriate for your locationID requirements, and whatever your field requirements might be.
Say locationID = 4 required Name, Address1, Address2 fields:
Page_Init(object Sender, EventArgs e)
{
TextBox txt = new TextBox(){
ID = "txtName"
};
plcDynamicControls.Controls.Add(txt); //Add to Form
dynamicControls.Add(txt); //Add to reference list, to avoid having to do .FindControl()
TextBox add1 = new TextBox(){
ID = "txtAddress1"
};
plcDynamicControls.Controls.Add(add1);
dynamicControls.Add(add1);
TextBox add2 = new TextBox(){
ID = "txtAddress2"
};
plcDynamicControls.Controls.Add(add2);
dynamicControls.Add(add2);
}
Build a nice loop to add controls like that to your placeholder.
In your .Click() event from your submit button you can iterate through the List<WebControl> dynamicControls collection and process the response.
i have been trying to create controls dynamically on my web page using the StringBuilder class..and i dont quite seem to get through...
any help would be appreciated.
i am trying to do this...
StringBuilder sbTest = new StringBuilder(string.Empty);
sbTest.Append("<input type=\"text\" id=\"txt1\" runat=\"server\" />");
Response.Write(sbTest.ToString());
The page for sure displays a TextBox on the browser which is easily accessible through JavaScript...but what i want is the control to be available on the Server Side too...so that when the page is posted back to the server i can easliy obtain the value that has been entered by the user into the textbox.
Can any 1 please help me with this....
thank you so much....
Like Torbjörn Hansson says, if you just add a name attribute (and maybe remove runat="server" from your original snippet) you'll be able to access the submitted value but you'll only have a client-side HTML <input /> element.
If you are wanting to dynamically create server-side controls then you'll have to do something like this:
TextBox textbox = new TextBox {
/* take care to create unique ID's if you're adding more than 1 TextBox */
ID = "foo",
Text = "bar"
};
Controls.Add(textbox);
In an answer almost about the something I answered this
You should do the things properly and not trying to reinvent the wheel.
Creating controls Dynamically you can choose 2 ways, the .NET way, or the Javascript way
Both are seen by any of the other, in other words, creating controls using the .NET way, javascript can see and use it and vice versa.
.NET way
in your HTML file add something like
<body>
<form id="form" runat="server">
<asp:PlaceHolder id="ph" runat="server" />
</form>
</body>
in your script part
TextBox txt = new TextBox();
txt.ID = "myTxt";
ph.Controls.Add(txt);
you can easily get that TextBox in javascript using:
var myTxtValue = $("#myText").value();
Javascript Way
var txt = $("<input />", {
id : "myTxt"
});
txt.AppendTo("body");
in .NET you get the value using
string value = Request["myTxt"];
NOTE All javascript lines uses jQuery for simplify results
Provide a name-attribute and access it with:
Request.Form["txt1"]
You can get the value from
Request["txt1"]