Can't reference controls in code behind. Visual Studio 2012 - asp.net

There are quite a few questions out there regarding this (for me, recurring) issue, but none of them have solved my problem.
Problem:
Whatever control I add in my aspx page, it is not recognised in the codebehind. Compiling doesn't work, because the ID is not recognised.
None of the following worked:
Clean and rebuild solution.
Close and open VS
Delete asp.net temp files
Check project's target framework.
Check assemblies are all there.
Check designer viewn to see if the control is actually there (it is)
Get control's ID with JS function to check it is the intended one (it is)
The problem has started only recently. In fact, I can reference the older controls fine.
The problem is observed both with standard ASP controls and Telerik ones.
Does anyone know of something else I should try? Please help me, I'm in the middle of a project and this is causing unnecessary delays, ta.

Make sure all of your asp.net controls (in the .aspx file) have the:
runat='server'
tag... Without this, you will not be able to reference the controls.
e.g.
<asp:Label runat='server' Text='Test Label' ID='TestLabel' />
Hope this helped...
Rodit

This is how I solved my issue. For a full account of it, please refer to the comments above.
I've noticed that although my project was already of web application type, designer files weren't showing.
I've forced the designer files to be recompiled by clicking on the ''convert to web application' option
I was then able to reference the control ID.
Thanks to the commentators anyway.

I was having a similar issue, due to the fact that I was using the pre-generated Login page. My solution was to change this section from this:
<asp:Login runat="server" ViewStateMode="Disabled" RenderOuterTable="false">
<LayoutTemplate>
To this:
<asp:Login ID="asplogin" runat="server" ViewStateMode="Disabled" RenderOuterTable="false">
<LayoutTemplate>
basically, I just added an ID to the asp:Login which allowed me to access the objects in the code from behind by prefixing the control name with asplogin
asplogin.youControlNameHere

Related

Modern HTML WYSWYG Editor for ASP.Net Web Forms application

I'm looking for some kind of HTML WYSWYG editor solution for an ASP.Net Webforms application. We currently use AjaxToolkit, but it doesn't support pasting images, is not really accessible, etc. I came accross FreeTextBox, but it seems to not support image pasting either, and it's been a big headache to configure properly given that the documentation is not all that descriptive. I've gotten the image gallery to work finally, but it looks pretty terrible, and I'm not sure the images will actually show up in the email (they were broken in my testing environment using the Papercut SMTP emulator). Just wondering if there are any other options I have with a Web Forms app, or am I limited to solutions that are as old as Web Forms?
you can try CKEditor(it have editable tool panel and spell checker)
https://ckeditor.com/cke4/builder
this free js library, easy integrate and if you want send result to .aspx.cs side should use call back by DevExpress control
I still use the ajaxtoolkit HTML editor. It is a bit dated, but I do find without any special settings, that I can paste in in images.
So, say I drop in a text box, use extender, and add HTML editor.
So, say this:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server" Width="1309px"
TextMode="MultiLine" Rows="40" ></asp:TextBox>
<ajaxToolkit:HtmlEditorExtender ID="TextBox1_HtmlEditorExtender" runat="server"
BehaviorID="TextBox1_HtmlEditorExtender"
EnableSanitization="False"
TargetControlID="TextBox1">
</ajaxToolkit:HtmlEditorExtender>
I am able to put a picture in my paste buffer, and a simple ctrl-v does paste the picture:
eg this:
As noted, I think the tool bar etc. does look quite outdated, but my experiance with the toolkit is that ctrl-v to paste in a picture does work.
As suggested, the other possible is ckedit, and it should work with asp.net web pages.
Its not clear why using the ajaxtoolkit editor does not allow cut + paste of images - my experience does seem to work. Perhaps you need sanitation=false?
As noted, the other suggestion here was CKEditor, and that seems like a good choice also.

Where is the code that runs when a button is clicked in ASP.NET

I'm trying to learn basic aspects of ASP.NET by analyzing the default Web Site project with Visual Studio 2010.
In the Register.aspx page there are fields for user registration and this button:
<asp:Button ID="CreateUserButton" runat="server" CommandName="MoveNext"
Text="Create User" ValidationGroup="RegisterUserValidationGroup"/>
The button does register an user, but I can't find the piece of code that is run and even less how code was associated to that button. I've tried searching the solution for all the identifier keywords and found nothing relevant. Searching on the web mentions a Button.OnClick method that I also can't find.
Any info on the basic aspects of ASP.NET will help me; thanks in advance.
Edit: hierarchically, the button is inside:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:CreateUserWizard ID="RegisterUser" runat="server" EnableViewState="false" OnCreatedUser="RegisterUser_CreatedUser">
<WizardSteps>
<asp:CreateUserWizardStep ID="RegisterUserWizardStep" runat="server">
<ContentTemplate>
<div class="accountInfo">
<p class="submitButton">
There is a RegisterUser_CreatedUser method on the code behind and it does:
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
string continueUrl = RegisterUser.ContinueDestinationPageUrl;
if (String.IsNullOrEmpty(continueUrl))
{
continueUrl = "~/";
}
Response.Redirect(continueUrl);
}
I was expecting some kind of inserting of user data on a database. I wonder, is this all that the button does?
The button you are looking it should be in CreateUserWizardStep control. I don't know much about this control but probably control looks for a child button having CommandName = "MoveNext", then it hooks for its click event.
Try changing the CommandName to something else like "test", it should NOT hit the breakpoint on RegisterUser_CreatedUser event.
Also note that CreatedUser <- event is telling that user is created, now the rest of the code is just authenticating the same user. Behind that, the user is already been created and saved in database.
If you also look in the web.config you will find this ConnectionString
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
Since you are using the Visual Studio's Default Web Application project, these all things are already done by Visual Studio for you.
An aspx page will also have a "code behind" file with the same name but a different extension (the letters after the dot) which depends on the language it's written in. Visual basic files have a .vb extension while C# files have a .cs extension.
Try looking for Register.vb or Register.cs and see if that's more fruitful.
If you're using a development environment like Visual Studio, you'll probably find that in the Solution Explorer you can click to expand the aspx file and see its code behind file underneath. If you're not, you might want to pick up a copy of the free express edition:
http://www.visualstudio.com/en-US/products/visual-studio-express-vs
When you find the code-behind, look for method called "MoveNext" - that's the code that'll run when you click the button, as specified by the CommandName attribute of the asp: Tag.
You've complicated a couple of things and you are completely not at fault but partly the project templates which comes with VS 2010 IDE. Let me try to help you one by one:
Learning basics of ASP.Net : For this you should be using "ASP.NET Empty Web Application" project template present in Visual Studio 2010. You've started with "ASP.NET Web Application" project template which has complicated things for
you. To start afresh "ASP.NET Web Application" looks the obvious choice for anyone though but it comes with a precooked boiler-plate code meant for ASP.NET membership forms authentication and its associated controls which is the root cause of all your confusion. To get started with the basics take the "ASP.NET Empty Web Application" project template I've suggested above and then add a new "Web Form" and then add various basic server web controls like button or text box to get started with concepts like event handling and code behind stuff.
Your other problem -
"The button does register an user, but I can't find the piece of code
that is run and even less how code was associated to that button"
That is because the button that you are seeing on Register.aspx page is
NOT an individual server web control but it is part of a composite control asp:CreateUserWizard instead. All the events of various controls be it a button, label or text box which are part of the asp:CreateUserWizard composite control is handled by the parent composite control asp:CreateUserWizard. You will NOT find all that code in your code behind file as this is present in System.Web.dll which is referenced in your project.
Since all the control events present on the composite control are handled by a common function written inside the code of composite control it has to distinguish exactly which control was clicked by the user (to take an appropriate action) which caused the current page post back for which CommandName property comes into picture. There is a switch case statement inside that common function for parent composite control which uses the CommandName property.
So essentially what happened is when you tried to start understanding basics of ASP.Net server web controls and event handling you actually got into the path of understanding ASP.Net Membership & role web server controls & providers which might be comparatively tough to understand and grasp initially. Hope this helps you to get started and further your understanding on ASP.Net world.

asp.net: Handling form data in Visual Studio 2010

Climbing the learning curve for creating asp.net webform pages with Visual Studio 2010 (VB).
I had written a fairly complicated .aspx page with form controls, including textboxes and buttons, etc. I never thought to place the form controls inside a <form> block. Instead, all the controls include the "runat" directive; for example, <asp:textbox id="txtUserName" runat="server"> etc. In the codebehind I access the data with strUserName = txtUserName.text. This seems to work just fine.
Now, though, I received some form pages from our contracted "professional" web developer wherein the form code is all enclosed in a <form runat="server">block, and none of the controls include the runat directive. Accessing the data from these controls is a little different: It uses the <input type="text name="txtUserName" id="txtUserName" /> method, and accessing the data in the codebehind
is strUserName = Request.Form("txtUserName").ToString.
My method seems to work fine, but I am wondering if there is a difference in behavior or reliability between my method and his. Even though my way works, am I doing it wrong?
Mine is based on online research I have done to learn this stuff, and I don't remember seeing anything that looked like his. However, just today I see places that are saying that on .aspx pages, form controls MUST be enclosed in a <form> block (i.e., this page at w3schools.com).
Can anyone clarify this for me?
Thanks for your help!
You're not doing it incorrectly (you're using my preferred approach) but your inputs should still be in an enclosing Form tag.
He's using HtmlControls (System.Web.UI.HtmlControls namespace) and you're using web controls (System.Web.UI.WebControls.) Your controls provide better functionality on the server (viewstate and accessing via server code) and his approach is lighter weight.

Is this asp compiled somehow?

I have an aspx document (I know nothing about asp, .net, aspx, nada). It is a normal html table structure for the most part, but there are strings of asp that seem to be inserting some sort of dynamic content. They are in the form:
<asp:Image ID="imgTopImage" runat="server" ImageUrl="~/Images/topbar.jpg" />
<asp:Label ID="lblStyleCaption" runat="server" CssClass="label_caption" Text="Theme: " Visible="false" />
<asp:DropDownList ID="dropStyles" Width="150" runat="server" AutoPostBack="true" />
It seems that whenever I delete one of these——something as innocuous as, say, the line with the asp:Image tag, which I would think should just remove the image, when I load the page I get run-time errors. It's very particular. My question is, is this compiled somehow, which is making it so fragile. Even just changing the topbar.jpg to something.png gives me an error. Do I need to track down the original files this was compiled from, or is this normal server-side asp(x?) that I'm just somehow else goofing up my changes to?
ASPX pages are compiled, and those tags refer to objects that are known to the server, so removing them could cause errors.
First, some basics in layman's terms
Tags that begin with ASP: (Example, <ASP:Button id="btnSubmit" runat="Server" Text="Click Me" />)
are not standard html buttons. They are server controls. When generating the html that goes out to the browser, the ASP.NET runtime looks at the server controls and creates the appropriate content depending on the browser visiting the page.
In the case of the Button control, it's usually a standard html button, but the runtime also generates the JavaScript and such to handle the button's server-side click event.
Why you're probably seeing errors when you remove a control:
Quite often, there's server-side code that's written that accesses these controls. For example, the developer may have decided to change the Text or the Visible property due to some event.
If this is the case, and you remove the <asp:Button> tag, then there will be server-side code that references an object that no longer exists in the aspx page, hence the errors.
More at these links on Server Controls:
http://www.w3schools.com/aspnet/aspnet_controls.asp
(Actually, this older one is better for a new-to-asp.net developer: http://msdn.microsoft.com/en-us/library/zsyt68f1(VS.71).aspx
http://support.microsoft.com/kb/306459
I'd also recommend taking some time watching basic videos or going through the tutorials at http://www.asp.net/get-started
I just noticed this in your question:
Even just changing the topbar.jpg to something.png gives me an error.
That is a bit odd, but I know of at least one way it could happen...
Generally, Visual Studio will give you a warning (and not an error) if you include a relative URL to an image or a linked page that doesn't exist. The warning shouldn't block you from compiling. However, Visual Studio does have a setting that tells it to treat warnings as errors. That will block it from compiling. Here's how that would be set up:
from Project Settings> Configuration Properties select the build
setting and change the “treat warnings as errors” settings to true.
If you wish to NOT treat warnings as errors, simply change the setting to false.

Presentation Error - SmartTarget Page

When I open an Webpage with SmartTarget configured, I am getting two different errors:
Error 1
First time I get this error:
Server Error in '/' Application.
--------------------------------------------------------------------------------
com/tridion/marketingsolution/profile/Contact
================================================
Some configured classpath roots cannot be found
================================================
ClassPath : C:\tridion\Publicationsites\TestRD\staging\bin\bin
I am not sure how Line 2, comes into the picture, but when I add another bin folder within the already existing bin folder, the error goes. Is something wrong with any of the config file?
Error 2
When I open the page after I apply the workaround for the above error, I receive the following error
Unknown server tag 'smarttarget:Query'.
<smarttarget:Query View="lister" AllowDuplicates="true" Timeout="5000"
Publication="tcm:0-14-1" runat="server" Id="as">
Line 3: <smarttarget:Item runat="server" TemplateUri="tcm:14-1319-32"
ComponentUri="tcm:14-1321"></smarttarget:Item>
Where do I need to add the smarttarget tag? Should it be in the web.config file? Can you please share the syntax. I have tried to accurately implement the ST as mentioned in the live docs. Any area that I need to recheck?
Question 3
I am pasting a screenshot of my Compound Page Template below:
When I publish this page, the HTML markup present in the Main Page Design TBB is not published at all. Only the markup generated by the Add SmartTarget to Promotion TBB exist in the aspx Page.
<smarttarget:Query View="lister" AllowDuplicates="true" Timeout="5000"
Publication="tcm:0-14-1" runat="server" Id="as">
<smarttarget:Item runat="server" TemplateUri="tcm:14-1319-32"
ComponentUri="tcm:14-1321"></smarttarget:Item>
<smarttarget:Promotions MaxItems="2" Region="sidebar" runat="server">
<ItemTemplate>
<smarttarget:PromotionalItems runat="server">
<ItemTemplate>
<tridion:ComponentPresentation runat="server"
PageURI="tcm:14-1119-64"
ComponentURI="<%# Eval("ComponentUri") %>"
TemplateURI="<%# Eval("TemplateUri") %>"/>
</ItemTemplate>
</smarttarget:PromotionalItems>
</ItemTemplate>
<FallbackContent>
<tridion:ComponentPresentation runat='server'
ComponentUri='tcm:14-1322'
TemplateUri='tcm:14-1323-32'/>
</FallbackContent>
</smarttarget:Promotions>
</smarttarget:Query>
Is my implementation correct ?
That's a lot of questions in one entry, but I'll try to answer them here.
Looks like you don't have the right Tridion home directory and it ends up checking 'bin' under the current directory instead. See my blog post on the subject on how this is figured out (and thus how you can solve it): How Tridion Content Delivery loads configuration files (.NET)
This is standard .NET functionality. You can define a prefix in the same page or, as recommended, in the web.config. The exact markup for the web.config is: <add tagPrefix="smarttarget" namespace="Tridion.SmartTarget.Web.UI" assembly="Tridion.SmartTarget" />
Only one "Output" item is used from the package (the last one added). So the way you've split up your Dreamweaver Templates currently would indeed mean that you only get the output from "ST Page Region". I don't know what the intention was with it, so I can't suggest a good way to solve it aside from getting rid of it and putting the tcdl:region directly inside "Main Page Design TBB".
Good luck with it :)

Resources