I am trying to get my HTML method below, to encode the string and display it on label, but I keep getting a blank page, on the client-side.
I have checked the viewsource and it shows no HTML output their also.
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e, string data)
{
if (!IsPostBack)
{
string a = createXMLPub(data);
// Label1.Text = HttpUtility.HtmlEncode(a);
Label1.Text = Server.HtmlEncode(a);
}
}
public static string createXMLPub(string data )
{
XElement xeRoot = new XElement("pub");
XElement xeName = new XElement("name", "###");
xeRoot.Add(xeName);
XElement xeCategory = new XElement("category", "#####");
xeRoot.Add(xeCategory);
XDocument xDoc = new XDocument(xeRoot);
data = xDoc.ToString();
return data;
}
HTML
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</asp:Content>
Please advice, to where I may be going wrong with this code. Many thanks
Your Page_Load isn't fired - re: the extra string data param doesn't match the signature for the event delegate
So:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string a = createXMLPub();
Label1.Text = Server.HtmlEncode(a);
}
}
public static string createXMLPub()
{
XElement xeRoot = new XElement("pub");
XElement xeName = new XElement("name", "###");
xeRoot.Add(xeName);
XElement xeCategory = new XElement("category", "#####");
xeRoot.Add(xeCategory);
XDocument xDoc = new XDocument(xeRoot);
return xDoc.ToString();
}
Hth...
Related
I have the following class (UCNewWorkFlow) which calls a cache database and retrieves rows and adds it to a string array:
public partial class UCNewWorkflow : System.Web.UI.Page
{
private string Connectioncacha = "";
public UCNewWorkflow()
{
int temp;
if (IsItWorkDay(DateTime.Now))
{
temp = 21;
}
else
{
temp = 17;
}
try
{
CacheConnection CacheConnect = new CacheConnection();
CacheConnect.ConnectionString = Connectioncacha;
CacheConnect.Open();
String SQLtext = #"";
DataTable table = new DataTable();
CacheCommand Command = new CacheCommand(SQLtext, CacheConnect);
CacheDataReader Reader = Command.ExecuteReader();
string[] inArr = new string[4];
int k = 0;
if (Reader.HasRows)
{
while (Reader.Read())
{
inArr[k] = Reader["NotYetSeen"].ToString();
returnTime(Convert.ToInt32(inArr[k]));
k++;
}
}
}
catch (Exception ce)
{
}
}
public string returnTime(int inHowMany)
{
string strTime = "";
double future = 0;
DateTime dt = DateTime.Now;
if (inHowMany / 2.0 <= 1)
{
strTime = "15 mins";
}
else if (inHowMany == 0)
{
strTime = "<15 mins";
}
else if (inHowMany / 2.0 > 1)
{
future = Math.Ceiling((inHowMany / 2.0)) * 15;
DateTime tempdate = dt.AddMinutes(future);
TimeSpan result = tempdate - DateTime.Now;
strTime = ToReadableString(result);
}
return strTime;
}
}
The result of the SQL query:
I have the following labels in my ASP.net page:
<asp:Label ID="lblFirstRow" runat="server" Text="Label"></asp:Label>
<asp:Label ID="lblSecondRow" runat="server" Text="Label"></asp:Label>
<asp:Label ID="lblThirdRow" runat="server" Text="Label"></asp:Label>
<asp:Label ID="lblFourthRow" runat="server" Text="Label"></asp:Label>
The code-behind for the ASP.net page:
protected void Page_Load(object sender, EventArgs e)
{
UCNewWorkflow uc = new UCNewWorkflow();
}
At the moment, I can't access the label from the class file.
How can I modify the code so, I have to call the class once and it will populate all four labels.
You are trying to perform this database query during the page's constructor, so it is too early in the ASP.NET Web Forms page lifecycle to have access to those arrays. Those labels do not exist when your constructor is called; they are created during the page initialization event.
As NicoTek suggested, using the Page_Load event handler is a good way of updating these labels. However, if you do it his way, I do not see a reason why your class is inheriting from System.Web.UI.Page, I would recommend refactoring your code so that this and any other database operations exist in another class. This will allow you to reuse code and prevent clutter and repetition in your code-behind files.
It looks to me that you want to return the string array inArr as a property of your UCNewWorkflow class and then bind this to a repeater on the Page_Load of your code-behind as suggested by #NicoTek.
Your Repeater definition on the code-in-front should contain just one Label definition and then as data is bound to the Repeater a new instance of the label is created for each element in your string array.
More details on repeaters can be found at
http://www.w3schools.com/aspnet/aspnet_repeater.asp
you could do
protected void Page_Load(object sender, EventArgs e)
{
UCNewWorkflow uc = new UCNewWorkflow();
lblFirstRow.Text = "someString"
}
I'm working on a website where there will be embedded a lot of YouTube videos. I want to make it a little easier to embed them into the articles of the page.
When writing this:
[youtube]SOMETHING[/youtube]
the page should automatically create this:
<iframe src="//www.youtube.com/embed/SOMETHING"
frameborder="0" allowfullscreen></iframe>
So - how do I do that? I've been searching around but haven't been able to find a right solution. Please throw your examples in ASP.NET / C#.
Creating shortcodes in ASP.NET is easy as a custom solution. Before you output your article do
String html = "[YOUTUBE]Something[\\YOUTUBE]";
String replacementHtml = "<iframe src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>";
Regex shortcodeRegex = new Regex(#"\[YOUTUBE\]([^\[\\]+)\[\\YOUTUBE\]");
String result = shortcodeRegex.Replace(html, replacementHtml);
Take note of the $1 in the replacementHtml. This is what is replaced by what is internal to the match.
Then output the result to the page.
Wordpress style short code application. It replaces the value [short code /] in the content coming from the database or in the variable in the variable with the user control content.
App_Code--> modul_islemler.cs
public class modul_islemler
{
public static string modul_olustur(string data){
string aranan = #"\[(.*?)\/\]";
Regex objRegex = new Regex(aranan);
MatchCollection objCol = objRegex.Matches(data);
foreach (Match item in objCol)
{data = data.Replace(item.Groups[0].Value, modul_yaz(item.Groups[1].Value.ToString()));
}
return data;
}
public static string modul_yaz(string sayfa)
{
string[] ayir = sayfa.Split(' ');
ArrayList myAL = new ArrayList();
foreach (string a in ayir)
{
myAL.Add(a);
}
if (myAL.Count < 2) myAL.Add("");
return LoadControl("~/plugins/" + myAL[0] + "/" + myAL[0] + ".ascx");
}
public static string LoadControl(string UserControlPath)
{
FormlessPage page = new FormlessPage();
page.EnableViewState = false;
// Create instance of the user control
UserControl userControl = (UserControl)page.LoadControl(UserControlPath);
page.Controls.Add(userControl);
//Write the control Html to text writer
StringWriter textWriter = new StringWriter();
//execute page on server
HttpContext.Current.Server.Execute(page, textWriter, false);
// Clean up code and return html
return textWriter.ToString();
}
public class FormlessPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
}
}
page.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="detail">
<div class="container">
<asp:Literal ID="icerikLtrl" runat="server"></asp:Literal>
</div>
</div>
</asp:Content>
page.aspx.cs --> [slide_plugins /] shortcodes
public partial class page : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
string txt="<div>blala [slide_plugins /] blabla</div>";
icerikLtrl.Text = modul_islemler.modul_olustur(txt);
}
plugins/slide_plugins/slide_plugins.ascx
<asp:TextBox runat="server" ID="Txt1"></asp:TextBox>
<asp:Button runat="server" ID="btn1" OnClick="btn1_Click" Text="Submit"></asp:Button>
plugins/slide_plugins/slide_plugins.ascx.cs
protected override void OnLoad(EventArgs e)
{
//kontrol yüklendiğinde çalışacak kodlar
base.OnLoad(e);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeComponent();
}
private void InitializeComponent()
{
btn1.Click += new EventHandler(btn1_Click);
}
protected void btn1_Click(object sender, EventArgs e)// not working....
{
Txt1.Text = "Example"; // not working....
}
This is what i use to handle youtube shortcodes
<Extension> Public Function ConvertYouTubeShortCode(text As String) As String
Dim regex__1 As String = "\[youtube:.*?\]"
Dim matches As MatchCollection = Regex.Matches(text, regex__1)
If matches.Count = 0 Then
Return text
End If
Dim width As Int32 = 620
Dim height As Int32 = 349
Dim BaseURL As String = "http://www.youtube.com/v/"
For i As Integer = 0 To matches.Count - 1
Dim length As Int32 = "[youtube:".Length
Dim mediaFile As String = matches(i).Value.Substring(length, matches(i).Value.Length - length - 1)
Dim player As String = "<div class=""video-container""><iframe width=""{2}"" height=""{3}"" src=""{4}{1}"" frameborder=""0"" allowfullscreen></iframe></div>"
Return text.Replace(matches(i).Value, [String].Format(player, i, mediaFile, width, height, BaseURL))
Next
End Function
~/Admin/AdimHome.aspx.cs C# code
protected void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>function Open() {");
sb.Append(string.Format("window.open('Chat.aspx?rid={0}'", lstRooms.SelectedValue));
sb.Append(", 'newwindow','toolbar=no,location=no,menubar=no,width=290,height=330,resizable=no,scrollbars=no,top=350,left=980,right=500');return false;");
sb.Append("}</script>");
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString());
}
lblFacultyNo.Text = Session["User_Id"].ToString();
lblUserType.Text = Session["User_Type"].ToString();
pnlChat.Visible = false;
}
~/Admin/Chat.aspx.cs page C# code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User_Id"] == null)
Response.Redirect("~/Admin/AdimHome.aspx");
if (string.IsNullOrEmpty(Request.QueryString["rid"]))
Response.Redirect("~/Admin/AdminHome.aspx");
txtMsg.Attributes.Add("onkeypress", "return clickButton(event,'btn')");
if (!IsPostBack)
{
hdnRoomID.Value = Request.QueryString["rid"];
ChatRoom room = ChatEngine.GetRoom(hdnRoomID.Value);
string prevMsgs = room.JoinRoom(Session["User_Id"].ToString(), Session["User_Id"].ToString());
txt.Text = prevMsgs;
foreach (string s in room.GetRoomUsersNames())
{
lstMembers.Items.Add(new ListItem(s, s));
}
}
}
want to pass lstRooms.SelectedValue to Chat.aspx.cs page to check as per client request to differentiate their chat rooms:
sb.Append(string.Format("window.open('Chat.aspx?rid={0}'", lstRooms.SelectedValue));
onclicking the btnChat event:
<asp:Button ID="btnChat" Runat="server" CssClass="btn" OnClientClick="JavaScript:Open()" OnClick="btnChat_Click" Text="Join Room" />
The simple solution to your problem could be if you want to change your code...
//Javascript function
function Open()
{
var ddl = document.getElementbyId('<%= lstRooms.ClientID%>');
var ddlvalue = ddl.options[ddl.selectedIndex].value;
Window.Open("Chat.aspx?rid=" + ddlvalue );
}
remove all the code for JS in pageload and put this on aspx page.
let me know if it solves
In the code behind of the master Page I create the meta tags:
HtmlMeta _metaDescription = new HtmlMeta();
_metaDescription.Name = "description";
_metaDescription.Content = "this is the description";
_metaDescription.ID = "metaD";
this.Page.Header.Controls.Add(_metaDescription);
HtmlMeta _metaKeywordsMaster = new HtmlMeta();
_metaKeywordsMaster.Name = "keywords";
_metaKeywordsMaster.Content = "here are the keywords" ;
_metaDescription.ID = "metaK";
this.Page.Header.Controls.Add(_metaKeywordsMaster);
HtmlMeta _metaTitleMaster = new HtmlMeta();
_metaTitleMaster.Name = "title";
_metaTitleMaster.Content = "TitlePage";
_metaDescription.ID = "metaT";
this.Page.Header.Controls.Add(_metaTitleMaster);
If I enter a specific contentpage I want to overwrite these meta tages by removing them and create new meta tags
HtmlMeta meta = (HtmlMeta)this.Header.FindControl("ctl00metaT");
this.Header.Controls.Remove(meta);
HtmlMeta _metaDescription = new HtmlMeta();
_metaDescription.Name = "description";
_metaDescription.Content = "NewDescription";
base.Master.Page.Header.Controls.Add(_metaDescription);
//this.Page.Controls.Add(_metaDescription);
HtmlMeta _metaKeywords = new HtmlMeta();
_metaKeywords.Name = "keywords";
_metaKeywords.Content = "NewKeywords";
base.Master.Page.Controls.Add(_metaKeywords);
//this.Page.Controls.Add(_metaKeywords);
HtmlMeta _metaTitle = new HtmlMeta();
_metaTitle.Name = "title";
_metaTitle.Content = "NewTitle";
base.Master.Page.Controls.Add(_metaTitle);
But it doesnt remove the old tags, I get double tags instead , what am I doing wrong ???
In order to overwrite the meta tag, you should write the below code on the load of the page
((System.Web.UI.HtmlControls.HtmlMeta)Page.Header.Controls[0]).Content = "IE=edge";
Of course you need to be sure to find the correct index of the control.
Here is a really simple solution, it works perfect for me:
http://lionfishtechnologies.com/developers/tips/c-sharp_add_meta_keywords_description_to_master_page.html
Follow these steps
1.Create a base page class for master page and put properties like below
public class MasterBasePage : System.Web.UI.MasterPage
{
private string _pageTitle;
private string _pageDescription;
public string PageTitle
{
get { return _pageTitle; }
set { _pageTitle = value; }
}
public string PageDescription
{
get { return _pageDescription; }
set { _pageDescription = value; }
}
protected override void OnLoad(EventArgs e)
{
if (string.IsNullOrEmpty(PageTitle))
{
_pageTitle = this.Page.Title;
}
_pageDescription = "Select from config file";
this.Page.Title = "Page Title";
HtmlMeta metaTag = new HtmlMeta();
metaTag.Name = "Description";
metaTag.Content = _pageDescription;
Page.Header.Controls.Add(metaTag);
base.OnLoad(e);
}
}
2.Inherit your master page class from BasePage
public partial class SiteMaster : MasterBasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
3.In the content page add following attribute(replace site.master with your own)
<%# MasterType VirtualPath="~/Site.master" %>
Override the master page base properties in the content page as below
protected void Page_Load(object sender, EventArgs e)
{
Master.PageTitle = "Page";
Master.PageDescription = "sadada";
}
I have a repeater control, and I want to put an unknown number of <asp:Hyperlink>s into the template, for example if you start with this:
<asp:Repeater runat="server" ID="PetsRepeater">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "Owner")%>
<%#this.ListPets(Container.DataItem)%>
</ItemTemplate>
</asp:Repeater>
and in code behind:
public partial class test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PetOwner p = new PetOwner() {
Owner = "Jimmy",
PetNames = new List<String>() { "Nemo", "Dory" }
};
List<PetOwner> PetOwners = new List<PetOwner>() { p };
PetsRepeater.DataSource = PetOwners;
PetsRepeater.DataBind();
}
}
protected String ListPets(Object PetOwner)
{
StringBuilder sb = new StringBuilder();
foreach (String Name in ((PetOwner)PetOwner).PetNames)
{
if (sb.Length > 0) sb.Append(", ");
sb.Append(Name);
}
return sb.ToString();
}
}
class PetOwner
{
public String Owner;
public List<String> PetNames;
}
Now suppose instead of having the string "Nemo, Dory" in my repeater, I want something like this:
<asp:HyperLink runat=server Text="Nemo" NavigateUrl="Pet.aspx?Name=Nemo" />,
<asp:HyperLink runat=server Text="Dory" NavigateUrl="Pet.aspx?Name=Dory" />
How can I do that? I tried putting a foreach inline in the aspx page, but I get the error Invalid expression term 'foreach'.
If you need to have an asp:Hyperlink control, and not just a simple tag, you should use a nested repeater.
http://msdn.microsoft.com/en-us/library/aa478959.aspx