ASP.NET Pageflow Info - c#

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.

Related

Kentico macro method inside template not working

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>

Treat external javascript file as part of Aspx Page

I know you can't use asp net server tags in an external javascript file. This is a bit of pain, because it forces you to declare your variables that need ClientID in the aspx page and then you refer to them in the external javascript file. Not very clean. Currently I use script manager's composite script to register my scripts... It would be nice if I could have the script injected and the server tags processed as if it was part of the page. Is this possible?
I know there is RegisterClientScript but this doesn't seem to honor the script tags either. I'm wondering if there is a solution someone has come up with to just pull the contents of the javascript file and shove them into the aspx page before it's processed so that the server tags can be processed. I've looked all over the web and don't see any good solution to this beyond using the server tags in the aspx page or generating the ids of controls, etc. server side and generating script.
I know you can't use asp net server tags in an external javascript
file
You can create an ASPX page to generate dynamic javascript
<%# Page Language="C#" AutoEventWireup="false"
CodeFile="script.aspx.cs" Inherits="scripts_script"
EnableViewState="false" StyleSheetTheme="" %>
function test() {
testinfo.innerHTML = "<%= MyVariable %>";
}
Make sure to set StyleSheetTheme="" otherwise the runtime will insert a <head> which you don't want
And in the code behind set the ContentType to application/x-javascript
using System;
public partial class scripts_script
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Response.ContentType = "application/x-javascript";
}
}
Now you can use this ASPX page as if it were a .js file.

how do I show a string as html content in web form

I am trying to retrieve a html document to show in my web page, now the content comes from database as a string. Now I know there is a way to do this in win forms using Browser.DocumentText. But how do I do this in web form?
I tried the setting the innerHTML property for a div inside of the "OnRowCommand", the "OnRowCommand" happens to be inside an update panel. When I move the Div outside the panel, say to just below the body, it renders well.
Well there are many ways to do this, you can use a label, literal Controls.
Or maybe defining a public string within your page then use it directly in your html as:
<%= strSomeString %>
Add a literal control in aspx file and in codebehind set
Literal1.Text=data_from_DB;
Try this one:
html code:
<div id="webcontent" runat="server">
</div>
Code behind:
webcontent.InnerHtml = FromDBstring;
Write up for Mvc app Html.Raw('html tages') or MvcHtmlString.Create('html tages') and for web form HttpUtility.HtmlEncode('html tages')

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.

Element-Enhancing Javascript in ASP.NET Master Pages

I have run in to a bit of a problem and I have done a bit of digging, but struggling to come up with a conclusive answer/fix.
Basically, I have some javascript (created by a 3rd party) that does some whizzbang stuff to page elements to make them look pretty. The code works great on single pages (i.e. no master), however, when I try and apply the effects to a content page within a master, it does not work.
In short I have a master page which contains the main script reference. All pages will use the script, but the parameters passed to it will differ for the content pages.
Master Page Script Reference
<script src="scripts.js" language="javascript" type="text/javascript" />
Single Page
<script>
MakePretty("elementID");
</script>
As you can see, I need the reference in each page (hence it being in the master) but the actual elements I want to "MakePretty" will change dependant on content.
Content Pages
Now, due to the content page not having a <head> element, I have been using the following code to add it to the master pages <head> element:
HtmlGenericControl ctl = new HtmlGenericControl("script");
ctl.Attributes.Add("language", "javascript");
ctl.InnerHtml = #"MakePretty(""elementID"")";
Master.Page.Header.Controls.Add(ctl);
Now, this fails to work. However, if I replace with something simple like alert("HI!"), all works fine. So the code is being added OK, it just doesn't seem to always execute depending on what it is doing..
Now, having done some digging, I have learned that th content page's Load event is raised before the master pages, which may be having an effect, however, I thought the javascript on the page was all loaded/run at once?
Forgive me if this is a stupid question, but I am still relatively new to using javascript, especially in the master pages scenario.
How can I get content pages to call javascript code which is referenced in the Master page?
Thanks for any/all help on this guys, you will really be helping me out with this work problem.
NOTES:
RegisterStartupScript and the like does not seem to work at any level..
The control ID's are being set fine, even in the MasterPage environment and are rendering as expected.
Apologies if any of this is unclear, I am real tired so if need be please comment if a re-word/clarification is required.
Put a ContentPlaceHolder in the head section of the master page, then add a asp:Content control on the content page referring to the placeholder and put your script in that control. You can customize it for each page this way.
Also, the reference by ID may not be working because when you use Master Pages, the control IDs on the page are automatically created based on the container structure. So instead of "elementID" as expected, it may be outputting "ctl00_MainContentPlaceHolder_elementID" View your source or use firebug to inspect your form elements to see what the IDs outputted are.
Isn't it possible to do with clean javascript ?-)
-- just add something similar to this inside the body-tag:
<script type="text/javascript">
window.onload = function(){
MakePretty("elementID");
}
</script>
By the way the script-tag has to have an end-tag:
<script type="text/javascript" src="myScript.js"></script>
Why not use jQuery to find all the controls? Something like this:
$(document).ready(function(){
$("input[type='text'], input[type='radio'], input[type='checkbox'], select, textarea").each(function(){
MakePretty(this);
});
});
This way you'll get all elements on the page, you can wait until the page is ready (so you don't modify the DOM illigally). The jQuery selector can get the elements in a bit more of a specific format if you need (ie, add a root element, like the ID of the body div).
It'd also be best to modify the MakePretty method so it takes the element not the ID as the parameter to reduce processing overhead.
Once you use Master Pages, the ids of controls on the client side aren't what you think they are. You should use Control.ClientID when you generate the script.
When using master pages, you need to be careful with the html attribute ID, since .NET will modify this value as it needs to keep ids unique.
I would assume your javascript is applying css styles via ID, and when you are using master pages the ID is different than what is in your aspx. If you verify your javascript is always being added, your answer needs to take into account the following:
ALWAYS set your master page id in page load (this.ID = "myPrefix";)
Any HTML element in your master page will be prefixed by the master page id (i.e.: on the rendered page will be "myPrefix_myDiv")
Any HTML element in your content place holder id will be prefixed with an additional prefix (i.e. myPrefix_ContentPlaceHolderId1_myDiv)
Please let me know if I can clarify anything. Hope this helps!

Categories