Kentico macro method inside template not working - c#

I have recently been working on Kentico sites, and the following issue has occurred recently, and never thought this won't work.
I have got a template on Kentico 8, and I want to display the content stored on 'ContentText' field of current document type.
So for this I am using the following code:
<cms:CMSDocumentValue runat="server" AttributeName="ContentText" FormattingString="{0}" />
which is working absolutely fine. However if I go and use a macro, as following:
<%# CurrentDocument.GetStringValue("ContentText", String.Empty) %>
it wouldn't pull the content stored on that field at all.
Do anyone know where I am going wrong? I am pretty sure the syntax is correct.
The reason why I want to use the macro is because I may be using this to check whether the value is null or not, so I can change the visibility of a placeholder.
Hope someone can help me on this.
Thank you.

Kentico macros (K#) are not getting resolved automatically in page template markup. Also, K# is not allowed in data-binding expressions (<%# ... %>). Generally, in page templates you can resolve macros using the following code:
<%# Import Namespace="CMS.MacroEngine" %>
<%= MacroContext.CurrentResolver.ResolveMacros("{% here comes your macro expression %}")%>
If I understand your question correctly you want to hide some asp:PlaceHolder control in the page according to value of current page field. This code might help you rather than invoking macro:
<%# Import Namespace="CMS.DocumentEngine" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
yourPlaceHolderControl.Visible = !String.IsNullOrEmpty(DocumentContext.CurrentDocument.GetStringValue("Intro", String.Empty));
}
</script>

Related

I need help identifying a programming technique so that I can research and fix it

The Code:
ParentControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ParentControl.ascx.cs"
Inherits="ParentControl" %>
<%# Register Src="~/ChildControl.ascx" TagPrefix="Prefix" TagName="ChildControlTag" %>
ParentControl.ascx.cs
public partial class ParentControl : UserControl
{
List<ASP.childcontrol_asxc> controlList = new List<ASP.childcontrol_asxc>();
... inside a public property setter ...
var control = new ASP.childcontrol_ascx(); // <ABC> what the heck is this reference?
controlList.Add(control);
...
}
ChildControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ChildControl.ascx.cs"
Inherits="ChildControl" %>
<asp:Repeater ID="childRepeater" runat="server" EnableViewState="false"
ViewStateMode="Disabled">
ChildControl.ascx.cs
public partial class ChildControl : UserControl
{
...
protected void Page_Load(object sender, EventArgs e)
{
childRepeater.DataSource = xyz; // <XYZ> crashes if I don't use the weird reference
}
}
The Problem:
I don't understand what the reference comment marked with <ABC> is all about. That's not the class I defined... but Intellisense doesn't complain. If I press F12 on it, it takes me to the <%# Control ... %> tag at the top of ChildControl.ascx instead of the control definition in ChildControl.ascx.cs.
I don't understand what this other version of the control is, why it's in the ASP namespace, or what the implications of using it instead of the control directly are. Worse, this compiles fine on my local workstation, but throws a compiler error on the TFS server we use for CI.
The Question:
Does anyone know the name for this method of using/referencing the custom User Controls, and/or have links/information I can look at to get a better handle on what this is and what the implications are? I've been unable to find anything useful via Google. While a fix/workaround would be great to have - I would still like to be able to research the technique.
Explorations:
I've tried replacing the usages with the actual class name, instead of the weird ASP.class_ascx references... it compiles fine if I do this, but unfortunately it fails at runtime. It seems like the other reference changes how it interacts with the asp.NET lifecycle - server controls defined in the aspx of the child control are null in the Page_Load() of the child control (marked <XYZ>). Under the weird ASP.control_ascx reference approach, the repeaters are properly defined when it hits the Page_Load() of the child controls, but I don't understand why.
Miscellaneous:
The project is using the Roslyn compiler on my local workstation, via the DotNetCompilerPlatform NuGet package but I believe its just using the VS/TFS 2015 built in compiler on the CI server. This might explain why TFS throws compiler errors - it tells me The type or namespace name 'usercontrol_ascx' does not exist in the namespace 'ASP' (are you missing an assembly reference?). I'm looking at configuring TFS to use the compiler from the NuGet package which will then hopefully compile - but this is still weird and I'd like to understand it.
This is the class that the ASPX file compiles to. It inherits your class and adds code that renders your ASPX content.

ASP.NET Pageflow Info

So I'm trying to use C# to grab stored HTML in a database and then display it between a set HTML header and footer (I have a couple of these for different pages, so a masterpage would make life more complicated rather than less. I also come from a PHP background where this is sort of the way things work).
<!--#include virtual="header.html" -->
<% #Page Language="C#" Debug="true" %>
<% #Import Namespace="System.Data.Odbc" %>
<% #Import Namespace="System.Web.Configuration" %>
<script language="C#" runat="server">
void Page_Load(object sender,EventArgs e) {
//Gets the HTML Successfully
//Response.Write(fetched_html);
}
</script>
<!--#include virtual="footer.html" -->
Unfortunately with the current workflow the code generates content before the header or footer are put on the page, putting all the stored HTML at the top of the page before the header. I've tried a couple different Page_Events and none of them seem to work, so I need to know what to do.
Is there an equally simple way to reference and insert a simple html header file that would render before any of the Page_Events? I've tried Page_PreLoad and others to no success. Either the code is not fetched at all or I run into the same issue.
Use a MasterPage with a ContentPlaceholder. Then, on the content page, use a Literal and put the HTML in there.
See "The difference between literal and label".
Try this:
Assuming you have data holding some where in memory like datatable or dataset or collection.
To display a html text on the page we generally use <asp:Literal/>. So place a asp literal control on the page. It works in between <body> </body> tag.
Now render the text to the control using its Text property. e.g.
ltl.text = dt.rows[0]["htmlcol"].tostring();
To dynamically add text inside <head> </head>, u need HtmlMeta,Page etc class.

How to add html to an aspx C# codebehind page?

I have access to a server with aspx pages. I need to add a title, parapgraphs, etc to a page. The page currently only has the following line:
<%# Page Language="C#" AutoEventWireup="true" Inherits="Access.Login" %>
I do not have access to the CS files, just the DLL. Anyway, when I try to add any html to the document nothing changes. I am able to change the CSS, and if I remove the "inherits" then whatever HTML I have gets displayed, but when the "inherits" is there only the default page gets displayed and none of my additions.
Admittedly I am new to ASP and moreover I am not trying to become a guru just to add some HTML to a page, but any advice would be great, thanks!
Try putting your Page_Load embedded in the .aspx and add controls that way:
<%# Page Language="C#" AutoEventWireup="true" Inherits="Access.Login" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
Controls.Add(whatever);
}
}
</script>
<!-- Try this if the above does not work -->
<script runat="server">
new protected void Page_Load(object sender, EventArgs e) {
base.Page_Load(sender, e);
if (!Page.IsPostBack) {
Controls.Add(whatever);
}
}
</script>
Fundamentally, I'm afraid this is not possible. .NET is a single-inheritance language/framework. So when it says Inherits="Access.Login" that means you can only have it use Access.Login OR your code-behind, but not both.
That said, you could jump through some crazy hoops to accomplish your goal. Like create a brand new "wrapper" page, then in the code-behind fire off an http request to the page you want. Load the response, which will just be a really long string into a 3rd-party DOM parser, or if you're confident you're getting 100% valid XML back, use .NET's built-in XmlDocument or XDocument to parse the page, find your html elements, make your changes, then do a Response.Write with your modified content.
And that's a real-life example of going around your elbow to get to your...
I am not 100% certain this will work, but you could have a code-behind file inherit from Access.Login and use the new (override will not work if Page_Load isn't marked as virtual) keyword with Page_Load. Then you could use Inherits="YourAssembly.NewLogin".
The part I am not sure about is whether or not asp.net uses the page class or your subclass to call the Page_Load method. If page_Load was virtual, it wouldn't matter, but since it isn't the new will only be called if the page is cast into your subclass. It is worth a try though.

ascx runat server script

I have default.aspx with a "Submit" Button and a code behind function called as "btn_Submit" which will perform submit action. Once I deploy the application and if there is any logical problem in btn_Submit code, then I can use runat=server script in default.aspx file and I need not go for another deployment.
But When I tried the same for ascx file, it works very well in development environment i.e in VS but when I move the same to Test server, system throws function not defined. I have renamed the existing function name.
So is it possible to add runat=server script and add c# code in ascx file?
Yes it is possible..
You have to surround your code with markup
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
//hello, world!
}
</script>
Take a look to thisquestion! I think it will help you..
But it is really better to separate your code..
Did you tell the button which method to run on submit? With "auto event wireup" it will try to find a "buttonname_Click" method if you didn't specify anything. If that doesn't exist, you will get an error.
To call a method with a different name, specify that in the OnClick property of the button.
I am not sure why this happened and still was not able to solve it, So redeployed the application :(

C# - ASP.NET Button click event not working

I have an ASP.NET (C#) page with some 3rd party controls, some ajaxy stuff and some normal ASP.NET Button controls.
The Button click events do not fire when clicked.
Double-clicking the button in design mode in VS 2008 switches to the code-behind but doesn't create the event handler.
Creating the event handler manually doesn't help.
The whole page is too big to include here, but this is the top bit:
<%# Page Language="C#" MasterPageFile="~/basewidepage2.master" AutoEventWireup="true" EnableEventValidation="false" CodeFile="CompanyCompliance.aspx.cs" Inherits="CompanyCompliancePage" Title="3DSS" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%# Register Assembly="obout_Grid_NET" Namespace="Obout.Grid" TagPrefix="cc2" %>
<%# Register Src="usercontrols/CalendarEx.ascx" TagName="CalendarEx" TagPrefix="uc2" %>
<%# MasterType VirtualPath="~/basewidepage2.master" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceholder1" runat="Server">
<script type="text/javascript">
// a bunch of function declarations
</script>
...and my button declaration on the page:
<asp:Button ID="LicenseCsvButton" runat="server" Text="Export to CSV" OnClick="LicenseCsvButton_Click" />
...and the code-behind:
protected void LicenseCsvButton_Click(object sender, EventArgs e)
{
// get data
CompanyCompliance cc = new CompanyCompliance(Master.theCompany.ID);
DataTable dt = cc.BusinessLicenses.Tables[0];
// send to browser as download
Tools.SendTableAsCsvToBrowser(Response, dt, "LicenseData");
}
Any ideas? could it be the ajax or something? Maybe the 3rd party "obout" grid control?
Update:
I did fix this a month or two ago, so I came back to this question to answer it for posterity but couldn't remember exactly how I fixed it! (Curse you, old age!) I had some limited success by replacing some of the ASP.NET AJAX controls with jQuery UI ones but I think the real solution was that one of the properties in the one of the tags was pointing to a control that no longer existed.
If you're in this same situation, try that and let me know what works in the comments and I'll post the correct answer.
During debugging, check the CausesValidation property of your button. For some reason, one of my pages had a button defaulting to "True." When I explicitly set it to "False" everything worked.
I know that this should be resolved by now, but just to share - I just had a similar issue. In my case, the problem was that I had a RequiredFieldValidator in a page, that wasn't visible because it was part of a popup. That validator was supposed to be invoked only when clicking its related "Save" button, but since I didn't have any ValidationGroup set, it would prevent the page to submit for any clicked button. Adding a ValidationGroup to the right button resolved the issue.
Experienced the same issue recently - cause was eventually determined to be that the button was disabled by a juavascript method onbeforesubmit (designed to prevent multiple submissions), and unfortunately web forms appears to check the enabled state of the button before it allows the codebehind event to trigger.
I had this problem just now and it was caused by another control having an AutoPostBack="true" which would submit the form before the button had a chance to submit the form to trigger the click event.
Change
CodeFile="CompanyCompliance.aspx.cs"
to
CodeBehind="CompanyCompliance.aspx.cs"
Related question: CodeFile vs CodeBehind
The inherits directive seems to point to a non-existant type.
Take a look in the code behind file of the CompanyCompliance page - ("CompanyCompliance.aspx.cs").
you should find the correct namespace and something like "public partial class xxx" where xxx is the name of the class which should correspond with your inherits directive. maybe you have to fully qualify the name as TJB already stated.
I had a similar issue, and it was really tricky. I recently migrated a VS 2005 ASP.NET 2.0 web forms app to VS 2010 ASP.NET 4.0.
It was difficult to setup and buggy as expected, but the issue of buttons not firing the click event was getting on my nerves.
In the end, it was as simple as not declaring a submit action in the site.master form. I changed:
<FORM runat="server" name="MainForm" method="post" action="Default.aspx" id="m_mainForm" enctype="multipart/form-data">
to
<FORM runat="server" name="MainForm" method="post" id="m_mainForm" enctype="multipart/form-data">
Boom. Problem solved. I hope it saves days of troubleshooting to someone. Sadly, I couldn't find anything about it on the internet by myself.
I had this problem I have changed the Button property "UseSubmitBehavior"=false. Now it is working.
For future answer seekers : If you are assigning the click handler in code behind, make sure that it is not inside an IsPostBack == false check :
void Page_Load (object oSender, EventArgs oEventArgs)
{
if (IsPostBack == false)
{
oButton += new EventHandler(oButton_Click); // does not work
}
oButton += new EventHandler(oButton_Click); // does work
}

Categories