.net ascx control not retaining value on postback (mojoPortal) - asp.net

I'm making a custom module for mojoPortal CMS which needs to allow the client to add an affiliate into the database. As far as I can tell, this requires creating a .ascx file and then installing that using the administration toolbar in the Web interface to get it to a point where I can put it into a page, as http://www.mojoportal.com/hello-world-developer-quick-start.aspx.
The form is simple enough, but the values in the text boxes just stay empty when I submit, though the file upload works fine. The code:
<asp:Label ID="Label1" runat="server" Text="Company Name" AssociatedControlID="CompanyName">
</asp:Label>
<asp:TextBox ID="CompanyName" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="Company Description" AssociatedControlID="CompanyDescription"></asp:Label>
<asp:TextBox ID="CompanyDescription" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:Label ID="Label3" runat="server" Text="Company Logo" AssociatedControlID="CompanyLogo"></asp:Label>
<asp:FileUpload ID="CompanyLogo" runat="server" />
<asp:Button ID="SubmitButton" runat="server" Text="Add Affiliate" />
EnableViewState for the page and the controls is enabled
The text box is not set to ReadOnly, and there is no funky JavaScript dynamically modifying elements (at least, I didn't set any).
I can work around this by using HTML elements, and get the values using Request.Form. The information is actually there, I can see it in the Request.Form, but I would have to get that by something like Request.Form[CompanyName.ClientId.Replace("_","$")] or Request.Form[6] which both seem very messy and IIRC aren't really the way things are supposed to roll in .NET. Besides, having worked until 3 last night, I really want to know what the answer is now!
Any thoughts anyone?

What I had done was not created a click event for the button, relying on the fact that it was posting to the server (like I would in PHP). Oops! When I added a click event, then the text boxes retained their value when I was within that method.

Related

How do I add a 'wrap' element to some asp tablerow elements in an ascx file so that I can hide/show them all with my vb code file?

I'm working with an older Server 2003 system and trying to create a new web form, based on other existing forms, which all follow certain conventions. (I'm guessing they were made with visual studio orignaly, but I'm not using this.) I'm not very fermiliar with asp/vb at all, I'm more of a PHP person, so I probably don't know the correct terms for lot a lot of the below.
I have an ascx file that contains my asp front end stuff in it. The main body has an asp table which is used when submitted the form to a database and sending it via email.
<asp:Table ID="inputTable" runat="server" CssClass="inputTable">
/stuff here
</asp:Table>
This contains various asp table rows like so:
<asp:TableRow id="someid" visible="false">
<asp:TableHeaderCell CssClass="LeftColumn">
<asp:Label ID="Label2" runat="server" Text="Some Field Label here"></asp:Label>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator" ControlToValidate="txt_somefield" Display="Dynamic" EnableClientScript="true" ErrorMessage="You must select an answer"> *</asp:RequiredFieldValidator>
</asp:TableHeaderCell>
<asp:TableCell CssClass="RightColumn">
<asp:TextBox runat="server" ID="txt_somefield" MaxLength="32" Width="98%"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
Some of these will be text fields, others drop downs etc.
I want to be able to 'group' several of these fields together so I can then use by code file (asxc.vb) to then do something like
Protected Sub ddl_someotherid_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ddl_someotherid.SelectedIndexChanged
If ddl_someotherid.SelectedValue.Contains("Yes") Then
somecollectionoffields.Visible = False
Else if ddl_someotherid.SelectedValue.Contains("No") Then
somecollectionoffields.Visible = True
End If
End Sub
If I try to put normal html elements in my asp file among the tags, then I will get an error such as System.Web.UI.WebControls.TableRowCollection must have items of type 'System.Web.UI.WebControls.TableRow'. 'div' is of type 'System.Web.UI.HtmlControls.HtmlGenericControl'.
So I understand that I need some kind of asp tag there instead. I'm looking for something that when the asp engine in the web server parses it, it comes out as something that will not mess up the html table the asp has generated, but can be used to hide/show several form elements based on the choices made in other drop down elements above in the form. (I understand the putting a div in between table rows in normal HTML would not be correct, it was just the last tag I tried before posting this.)
If this were PHP, I could just 'interupt' the HTML table with a PHP tag, do my calculations to determine if the set of fields should be shown, then close the tag, but I don't know how to do this in asp/vb.
I did do some searching and found some slightly different questions that shows a asp tag called a panel using something like <asp:panel> but this results in a similar error to above, just telling me that this is not allowed also.
I don't really want to close the overall <asp Table> tag to do this, because this is used to grab the form contents to put it in an email, in the vb file and I don't know how to re-write that to compensate.
Ok, शेखर has sort of helped me come to the realisation that I needed with his comment that
There is a server control (<asp:) corresponding to every html control.
Once I realised that all these asp: tags are just proxy's for actual html tags I realised that the asp parser is just trying to protect me from my own stupidity in creating invalid HTML at the other end. You cannot break up a table by enclosing some of it in a div in HTML, so asp won't let me do it either. I just needed to nestle one table inside another then show and hide the nestled one to achieve what I wanted. It was never about the vb side of things or the more advanced asp stuff.
So like this:
<asp:TableRow id="someid" visible="false">
<asp:TableHeaderCell >
<asp:Table ID="subinputTable" runat="server" CssClass="subinputTable">
<asp:TableRow id="testfield1" >
<asp:TableHeaderCell CssClass="LeftColumn">
<asp:Label ID="Label3" runat="server" Text="Test Field 1"></asp:Label>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator3" ControlToValidate="txt_test1" Display="Dynamic" EnableClientScript="true" ErrorMessage="You must fill in this field"> *</asp:RequiredFieldValidator>
</asp:TableHeaderCell>
<asp:TableCell CssClass="RightColumn">
<asp:TextBox runat="server" ID="txt_test1" MaxLength="32" Width="98%"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:TableHeaderCell>
</asp:TableRow>
This then works just fine. I can't promice it's the best or most elegant solution, but it's what I was looking for.

ASP.NET closing tag

When I use autocompletion in VisualStudio 2010 within my .aspx application, there are different default completions at closing control tags:
<asp:CheckBox />
<asp:Label></asp:Label>
Is there a explaination for this behaviour?
<asp:CheckBox></asp:CheckBox>
<asp:Label />
Wouldn't be invalid.
This is because ASP.NET's Label control is decorated with the ParseChildrenAttribute, with ParseChildren(false) while CheckBox isn't.
You can support the same behavior whith your custom controls, for example, with the following code, Visual Studio will behave like Label if you use MyControl in the web form editor:
[ParseChildren(false)]
public class MyControl : WebControl
{
...
}
The label closing is like that
<asp:Label runat="server"></asp:Label>
because usually we type something between
<asp:Label runat="server" ID="lblOne">better start programming now</asp:Label>
that is not the case for checkbox, that we type inside of it
<asp:CheckBox runat="server" Text="enable" ID="cbOne" />
We have on both elements the Text field, why on the one we prefer to write out side... Look at this example, on Label, or On other similar controls the text that we may have to write may include characters that are not allowed inside the Text Property, maybe a complex css style or what ever... The check box from the other side is only include a small text (yes, not, something like that)
<asp:Label ID="lblLabel" runat="server">
This is a <b>"label"</b>
<br />And one more line
</asp:Label>
and more example that compiles
<asp:Label ID="lblLabel" runat="server">
This is a <b>"label"</b>
<br />And one more line
<asp:Literal runat="server" ID="ltrOneMore">One more Control Inside</asp:Literal>
</asp:Label>
---but this is not compile--
<asp:Label ID="lblLabel2" runat="server"
Text="This is a <b>"label"</b>
<br /> and one more line"
/>
At the final end is a decision that the makes make - maybe we need to ask them for the real real reason.
Now this is also not compile
<asp:CheckBox runat="server" ID="cbMyChbx">one<asp:CheckBox>
check box when is render on page is use two controls, one input and one label, so they maybe need to help user to understand that the text is not going on the input control.
<asp:CheckBox />
Because the element has no content, you can close the tag with /> instead of using a separate closing tag
<asp:Label></asp:Label> or <asp:Label />
Displays static text on a Web Forms page and allows you to manipulate it programmatically.
Learn more about it Web Server Control
All the answers above are valid, but something additional. All the asp controls are eventually rendered as HTML controls and that also defines how the asp controls behave. For e.g. it is not necessary that text in a label is always set as
<asp:Label runat="server" ID="lblOne">better start programming now</asp:Label>
it can be also done as follows
<asp:Label runat="server" ID="lblOne" Text="better start programming"></asp:Label>
now both are correct format, so it is not valid to say that any control which needs content will have a separate closing tag. It also depends on how it rendered in HTML. for e.g by default asp Label is rendered as a span and doesnt conform to XHTML standards. Hope this makes it clear, always think of how it will be rendered and ASP tries to adhere to what eventually will be rendered.
cheers

Is it possible to avoid rendering the error message from an ASP.Net validator control until the validator is evaluated as invalid?

Considering the fact that I was not able to find a single instance of someone else needing this functionality anywhere else, this might be an off the wall requirement. That said:
A website that I am working on uses several dozen different validator controls (everything from RequiredFieldValidaotrs to CustomValidators) throughout for form validation. As part of our Section 508 compliance, we have to support users who disable CSS, which is problematic because the validators render the error text to the page and use the CSS display property to hide it. When CSS is disabled all of the error messages are both visible and read by screen readers.
Short of using labels and postbacks to show and hide said labels, is there any known method for using ASP.Net validator controls with CSS disabled?
Use the Display="None" attribute on the FieldValidator control and a ValidationSummary tag to contain the messages.
<form id="form1" runat="server">
<asp:TextBox runat="server" ID="TextBox1" /> <br />
<asp:TextBox runat="server" ID="TextBox2" /> <br />
<asp:Button runat="server" Text="Go" />
<div class="messages">
<asp:ValidationSummary id="summery1" runat="server"/>
</div>
<div>
<asp:Panel ID="Panel1" runat="server" >
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Required Field Validator1 empty" ControlToValidate="TextBox1" Display="None" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ErrorMessage="Required Field Validator2 empty" ControlToValidate="TextBox2" Display="None" />
</asp:Panel>
</div>
</form>
HOWEVER....(there's always a catch)... with this method, the Validation Messages themselves are stored in the JavaScript only. Meaning that it won't work if Javascript is disabled. I'm assuming that's not a huge problem since you are working in WebForms (which rely on JS), but I figure it's worth mentioning.
And for the record, accessibility concerns are mostly a crock of horse-crap. I THOUGHT I knew about accessibility until I actually worked with a visually impaired programmer (100% blind). Then, I learned that JS works just fine (assuming they know to look for new content...) and that they just skip around the page from link to link until they find what they are after. And table-based layouts didn't slow them down for 1 second. Boy that was a tough pill to swallow after being SOOO unbearably preachy about CSS for a few years....

Updating Database with value from datepicker control ASP.NET VB

Apologies in advance, for what may be a newbie question. (new to asp.net, coding in VB, zero knowledge of best controls). Please respect that I am not interested in AJAX controls, or using MVC and trying to minimise javascript. What I need to do is very simple in terms of technology.
I am developing a form that allows users to Edit database data. I have chosen to use FormView so that I can format it like a legacy vba app. I am able to set the data source to my database table and the values from the database successfully show up if I allow VWD to automatically format the control. I can edit everything in the database using this form as well.
However, the boss hates having to type dates.
I haven't been able to find a datepicker control with a datasource feature that works like the text boxes that are automatically built in formview (with a bind to a datasource feature). So, I am assuming none exist. I need some assurances that what I think I need to do is the right way.
Instead of using the FormView control's datasource via the front-end automagical stuff, I should instead
place one of these datapicker controls that simply combine calendar with a text box for all date fields in the formview (no disrespect to those who built them, just can't believe they are not more feature-rich, this seems so needed giving the number of datepickers available)
declare my data source in Page_Load and load all the controls if they have existing data utilising FindControl
use Data_Bound block to retrieve the selected values from each control utilising FindControl and build a dynamic SQL string for Update
declare and update my database using one of the code behind blocks, perhaps in the DataBound
Am I on the right track? I have no experience to be confident in my assumption.
and please, if there is an easier way, I'll take it, but I have to make it "pretty".
And suggestions for controls of any sort are welcomed.
---Further into my issue
Here is some code to prove I've actually tried to resolve this...
In my FormView code block I have:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="MASTERID_Action"
DataSourceID="srcAction">
<EditItemTemplate>
MASTERID_Action:
<asp:Label ID="MASTERID_ActionLabel1" runat="server"
Text='<%# Eval("MASTERID_Action") %>' />
<br />
Action_Description:
<asp:TextBox ID="Action_DescriptionTextBox" runat="server"
Text='<%# Bind("Action_Description") %>' />
<br />
Action_Target:
<asp:TextBox ID="Action_TargetTextBox" runat="server"
Text='<%# Bind("Action_Target") %>' />
<br />
Action_Captured:
<asp:TextBox ID="Action_CapturedTextBox" runat="server"
Text='<%# Bind("Action_Captured") %>' />
<br />
Action_Declined:
<asp:TextBox ID="Action_DeclinedTextBox" runat="server"
Text='<%# Bind("Action_Declined") %>' />
<br />
Action_AgreedDate:
<ewc:CalendarPopup ID="CalendarPopup1" runat="server" Culture="en-AU"
PostedDate="" SelectedDate='<%# Bind("Action_AgreedDate") %>'
SelectedValue="01/14/2013 08:47:54" UpperBoundDate="12/31/9999 23:59:59"
VisibleDate="01/14/2013 08:47:54" />
<br />
...
</EditItemTemplate>
My database holds this Action_AgreedDate as nullable.
When I view the ItemTemplate (in the browser) the date shows up as 0.000 (because its a text field and bound to Action_AgreedDate, no error occurs) and when I click Edit to go to the EditItemTemplate I get this error:
Conversion from type 'DBNull' to type 'Date' is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Conversion from type 'DBNull' to type 'Date' is not valid.
Source Error:
Line 95:
Line 96: Action_AgreedDate:
Line 97: '
Line 99: SelectedValue="01/14/2013 08:47:54" UpperBoundDate="12/31/9999 23:59:59"
I can easily translate this into "the control found a null field and doesn't know what to do with it"; problem is, I don't know what to do. I have checked the properties of the field (the CalendarPOP field to see if there is a setting for handling nulls and nothing is obvious to me. I'm currently trying to find further documentation on the control online. (I've contacted eWorld and hope they will be able to respond.)
I should also add that if I request a record that already has an Action_AgreedDate I get no errors because there is a value present in the database for the control to display.
I think the best way for you to do this would be to use jQuery and jQuery UI, which has a date picker, which can be attached to a regular ASP.NET TextBox in your FormView. So if you had FormView code that looks something like this for example:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="id" DataSourceID="SqlDataSource1">
<EditItemTemplate>
id:
<asp:Label ID="idLabel1" runat="server" Text='<%# Eval("solution_id") %>' />
<br />
date_modified:
<asp:TextBox ID="date_modifiedTextBox" runat="server" Text='<%# Bind("date_modified") %>' />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
id:
<asp:Label ID="idLabel" runat="server" Text='<%# Eval("solution_id") %>' />
<br />
date_modified:
<asp:Label ID="date_modifiedLabel" runat="server" Text='<%# Bind("date_modified") %>' />
</ItemTemplate>
</asp:FormView>
You could run something like this using jQuery UI to get a datepicker on the date_modified text box:
$('[id$=date_modifiedTextBox]').datepicker()
The $('[id$=date_modifiedTextBox]') part is necessary to select the ASP.NET control using jQuery, if it were just a normal element you could just use $('.className') or $('#id') or something like that. Hope this helps.
Problem solved.
I ran across an article on 4GuysFromRolla.com about the RJS POP Calendar (http://preview.tinyurl.com/cerm9xv) and it ticked all the boxes. Successfully implemented it and, because the calendar is separate from the specified text box, it doesn't have to be bound ! It works very nicely. The 4GuysFromRolla save my bacon yet again...

ASP.Net Localization & Bound controls

When I localize an asp.net page that is using bound controls (DetailsView, etc) that has TemplateFields bound using the <%# Bind() #> syntax, after the localization all of the bindings are removed and I have to go back in & rebind everything. I'm creating the localized resource file by switching to design view, then Tools / Generate Local Resource from the menu.
Has anyone else seen this problem, and if so, do you have any suggestions for a workaround?
Before:
<asp:TemplateField HeaderText="First Name:">
<InsertItemTemplate>
<uc:FirstNameTextBox runat="server" ID="FirstName" ValidationGroup="Main" Text='<%# Bind("FirstName") %>' />
</InsertItemTemplate>
</asp:TemplateField>
After:
<asp:TemplateField HeaderText="First Name:" meta:resourcekey="TemplateFieldResource1">
<InsertItemTemplate>
<uc:FirstNameTextBox runat="server" ID="FirstName" ValidationGroup="Main" />
</InsertItemTemplate>
</asp:TemplateField>
Edit: Looks like its just my own UserControls that lose the binding. I tried adding the Bindable and Localizable(false) attributes to the properties, but that didn't seem to help.
Just found this... http://blog.smart-ms.ordina.nl/Generate+Local+Resource+Files.aspx
Seems to do the trick without mangling your ASPX file at all... I've not run it over a master page / user control yet.
Yes! I had this happen to me, but just on user controls as well. Is this a normal problem then? I don't know how to resolve it though.
Out of interest, is there any alternative to using Tools -> Generate Local Resource from the menu for building resource files??? I generally already attach my meta:resourcekey tags onto my localizable content controls and don't want it to change it for anything else.

Resources