I have created a user control and registered inside asp.net page and
used that user control also. Everything works fine but user control
code executing repeatedly and thsi cycle goes on. I am not able to
find why this user control code keep on executing, Any help would be
highly appreciated.
Header.ascx code
<%# Control Language="C#" AutoEventWireup="true" Inherits="SSBilling.UserControl.header" %>
<script language="C#" runat="Server">
public void buffer()
{
try
{
Response.Buffer = true;
}
catch
{
}
}
public string cleanupCookie(string cookie)
{
string tmpcookie = cookie.Replace("%28", "(");
tmpcookie = tmpcookie.Replace("%29", ")");
tmpcookie = tmpcookie.Replace("%27", "'");
tmpcookie = tmpcookie.Replace("%2E", ".");
tmpcookie = tmpcookie.Replace("%3F", "?");
tmpcookie = tmpcookie.Replace("%2C", ",");
tmpcookie = tmpcookie.Replace("%5F", " ");
tmpcookie = tmpcookie.Replace("%2D", "-");
tmpcookie = tmpcookie.Replace('_', ' ');
tmpcookie = tmpcookie.Replace("ITEMCLICK2", "itemClick2");
return tmpcookie;
}
</script>
<%
//************************************************************************************************
//* 2012-06-05 HRHC
//* * migration updated
//************************************************************************************************
buffer();
%>
<script language=vbscript>
sub printthis()
window.focus()
window.print()
end sub
sub backbutton()
on error resume next
<%
Response.Write("' " + ((Request.Cookies["mID"] == null) ? String.Empty : Request.Cookies["mID"].Value) + "\r\n");
//response.write "self.parent.document.all.tmp.tmpMenu.value = """ & cleanupCookie(request.cookies("mID")) & """" & vbcrlf
Response.Write("top.document.all.tmp.tmpMenu.value = \"" + cleanupCookie((Request.Cookies["mID"] == null) ? String.Empty : Request.Cookies["mID"].Value) + "\"" + "\r\n");
//response.write " if instr(1, """ & request.cookies("deptlist") & """, "","" & self.parent.document.all.tmp.currDept.value & "","") > 0 then " & vbcrlf
Response.Write(" if instr(1, \"" + ((Request.Cookies["deptlist"] == null) ? String.Empty : Request.Cookies["deptlist"].Value) + "\", \",\" & top.document.all.tmp.currDept.value & \",\") > 0 then " + "\r\n");
Response.Write(" if err.number <> 0 then exit sub " + "\r\n");
Response.Write("top.go \"visible\"" + "\r\n");
//response.write "self.parent.document.all.menuadmin.style.visibility = ""visible""" & vbcrlf
Response.Write("else" + "\r\n");
Response.Write("top.go \"hidden\"" + "\r\n");
//response.write "self.parent.document.all.menuadmin.style.visibility = ""hidden""" & vbcrlf
Response.Write(" end if " + "\r\n");
//what?
//Session("CurrentUserAdmin") = "Y"
%>
end sub
' 2012-04-04 HRHC
' - modified to avoid scripting error after migrated
' the following if statement only works when the
' child and parent frames are under the same domain
'----------------------------------------------------
'If IsObject(self.parent.document.frames) Then
' If self.parent.document.frames.length = 0 Then
' loc = InStr(8, self.location.href, "/")
' loc = Mid(self.location.href, loc)
'
' location.href = "/default.asp?loc=" & loc
' Else
' Call backbutton
' End If
'End If
</script>
<script type="text/javascript">
if (top === self) {
/*
2012-08-18 HRHC
- no in the trinity frameset (both zone and new app), call the default page.
this will no longer be used after app migrated
*/
var loc = "";
top.location = "/default.aspx?loc=" + loc;
}
else {
/*
- in the frameset, do nothing
*/
}
</script>
<link REL="stylesheet" TYPE="text/css" HREF="/include/content.css">
<%
//response.write "hello from header.inc<br />"
%>
Registerd in asp.net page like this:
<%# Register TagPrefix="uc" TagName="header"
Src="~/UserControl/header.ascx" %>
And called the header.ascx like this:
<uc:header id="ucHeader" runat="server"></uc:header>
Thank You!
Related
How do I set the code below to generate email with high priority in the subject line? Thank you for any guidance.
Private Sub SendEmail(ByVal pharmEmail As String, ByVal backupEmail As String)
Dim smtpClient As New System.Net.Mail.SmtpClient()
Dim message As New System.Net.Mail.MailMessage()
Try
Dim fromAddress As New System.Net.Mail.MailAddress(WebConfigurationManager.AppSettings("EmailFromAddr"), WebConfigurationManager.AppSettings("EmailFromName"))
message.From = fromAddress
message.To.Add(pharmEmail)
message.Subject = WebConfigurationManager.AppSettings("EmailSubject")
If (WebConfigurationManager.AppSettings("backupEnabled") = True) Then
message.CC.Add(backupEmail)
End If
message.IsBodyHtml = True
Dim orderURL As New HyperLink
orderURL.Text = "here"
orderURL.NavigateUrl = "http://" & WebConfigurationManager.AppSettings("ServerName") & "/User/ReviewOrder.aspx?orderID=" & webOrderID
message.Body = "An order was created using the account of " + Profile.FirstName.ToString() + " " + Profile.LastName.ToString() + ". " + WebConfigurationManager.AppSettings("EmailBody") + "<a href='" + orderURL.NavigateUrl + "'>here.</a>"
'message.Body = WebConfigurationManager.AppSettings("EmailBody") & " " & orderURL.
smtpClient.Send(message)
Catch ex As Exception
ErrorHandler.WriteError(ex.ToString)
Throw ex
End Try
I believe you can set the Priority property on the MailMessage. See MSDN for more details.
I am a newcomer in .net , my problem is related to email. This code is well performed on my localhost. This is code of my enquiry.aspx.cs:-
protected void Button1_Click(object sender, EventArgs e)
{
Mail mm = new Mail();
if (DropDownList3.SelectedItem.Text == "--Select--")
{
Label5.Text = "Please Select Course";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Name');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Name'); </script>");
}
else if (TextBox1.Text == "")
{
Label5.Text = "Please Enter Name";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Name');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Name'); </script>");
TextBox1.Focus();
}
else if (mm.checkValidemail(TextBox2.Text) == false)
{
Label5.Text = "Please Enter E-Mail ID";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter E-Mail ID');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter E-Mail ID'); </script>");
TextBox2.Focus();
}
else if (mm.checkValidmobile(TextBox3.Text) == false)
{
Label5.Text = "Please Enter Mobile Number";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Mobile Number');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Mobile Number'); </script>");
TextBox3.Focus();
}
else
{
myenquiry ee = new myenquiry();
//myenquiry ee=new myenquiry();
int i = ee.add_enquiry(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text, "-", "-", "NORMAL ENQUIRY FROM SITE", TextBox11.Text, DropDownList3.SelectedItem.Text, TextBox12.Text,locationlst.SelectedItem.Text);
if (i == 1)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(" Enquiry " + "<shila#gmail.com> ");
message.To.Add(new MailAddress("shu#gmail.com"));
message.CC.Add(new MailAddress("va_aone#yahoo.com"));
message.Subject = "Enquiry from CMC site";
string p = "<b>Name: </b>" + TextBox1.Text;
p += "<br><b>Mobile:</b> " + TextBox3.Text;
p += "<br><b>Mail ID:</b> " + TextBox2.Text;
p += "<br><b>Address:</b> " + TextBox4.Text;
p += "<br><b>City:</b> " + TextBox5.Text;
p += "<br><b>Location:</b>" + locationlst.SelectedItem.Text;
p += "<br><b>College:</b> " + TextBox11.Text;
p += "<br><b>Course:</b> " + DropDownList3.SelectedItem.Text;
p += "<br><b>Query:</b> " + TextBox12.Text;
message.Body = p;
message.IsBodyHtml = true;
SmtpClient SMTPServer = new SmtpClient("localhost");
try
{
SMTPServer.Send(message);
//result = "Your Enquiry has been Submitted !!";
Label5.Text = "Your Enquiry has been Submitted !!";
//Response.Write("<script language=JavaScript> alert('Your Enquiry has been Submitted !!'); </script>");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox11.Text = "";
TextBox12.Text = "";
DropDownList3.SelectedIndex = 0;
}
catch
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
//Response.Write("<script language=JavaScript> alert('Server Problem !!Your Enquiry Not Submitted'); </script>");
}
}
else
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
}
}
and this is my appcode folder enquiry.cs:-
public class myenquiry
{
SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=group;Integrated Security=True");
SqlCommand comm = new SqlCommand();
int result = 0;
public int add_enquiry(string nam,string email,string mob,string adr,string cit,string state,string country,string zip,string college,string tech,string query,string loc)
{
try
{
comm.Connection = conn;
comm.CommandText = "insert into enquiry(name,email,mobile,address,city,state,country,zip,college,technology,query,edate,location) values('" + nam + "','" + email + "','" + mob + "','" + adr + "','" + cit + "','" + state + "','" + country + "','" + zip + "','" + college + "','" + tech + "','" + query + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','"+loc+"')";
conn.Open();
comm.ExecuteNonQuery();
result = 1;
}
catch(Exception ee)
{
result = 0;
}
finally
{
conn.Close();
}
return result;
}
}
this is well perform on local. But at the server the appcode enquiry.cs is not called on enquiry.aspx.cs and the value of int i is becoming 0, so the else part is executing. Why?
You seem to have a hard coded connection string in the myenquiry class. If you are not dynamically setting the connection string from a configuration file or otherwise, the insert method will try to use that string which points to your local. Assuming your server is a different domain/machine with no access to your local DB, the connection will definitely fail, giving you the result 0.
As Shree.pat18 says Don't make hardcodded connection string in class file.instead of this make your connection string in web.config file something like this in your configuration tag
<connectionStrings>
<add name="cn" connectionString="Data Source=USER-PC;Initial Catalog=group;Integrated Security=True"/>
</connectionStrings>
there are loads of resources that show how to use global.ascx global error event handler to capture un-managed errors in the web application but i am yet to find a good sample of code to include in this method that will report on major topics like error message, an output of stack trace, page that generated the error, the user-name/ role that generated the error... and the such.
has anyone used, have, or come across a nice code spinet for this purpose?
thanks in advance.
Your best best it to do nothing. ASP.NET Health Monitoring will write an event to the event log containing most of the data you could need.
If that's not enough information for you, then you should look into wrapping certain of your exceptions in an outer exception which includes the additional data. For instance:
string fileSpec = " ... ";
try
{
using (var stream = new FileStream(fileSpec))
{
// Something
}
}
catch (IOException ex)
{
throw new Exception(String.Format("Error processing {0}", fileSpec), ex);
}
Here's what we're using though we may now want to switch to Health Monitoring seeing the other answers to this question.
public static void LogErrorWithStackTrace(String message, Exception exception,
EventLogEntryType entryType)
{
var context = HttpContext.Current;
var session = context.Session;
var request = context.Request;
var errorMessage =
String.Format(
#"Message: {0}
Error in: {1}
Referer: {2}
Agent: {3}
IP: {4}
Request type: {5}",
message, request.Url, request.UrlReferrer,
request.UserAgent, request.UserHostAddress, request.RequestType);
errorMessage += "\rQuery string variables:";
errorMessage = request.QueryString.Keys.Cast<string>().Aggregate(errorMessage,
(current, key) =>
current +
"\r " + key + " = " +
request.QueryString[
key]);
errorMessage += "\rForm variables:";
errorMessage = request.Form.Keys.Cast<string>().Aggregate(errorMessage,
(current, key) =>
current + "\r " + key +
" = " +
request.Form[key]);
errorMessage += "\rCookies:";
errorMessage = request.Cookies.Keys.Cast<string>().Aggregate(errorMessage,
(current, key) =>
current + "\r " + key +
" = " +
request.Cookies[key]);
if (session != null)
{
errorMessage += "\rISession:";
var sess = (ISession) session["session"];
errorMessage += sess.ToString();
errorMessage += "\rSession:";
errorMessage = session.Keys.Cast<string>().Aggregate(errorMessage,
(current, sessionKey) =>
current +
"\r " + sessionKey + ": " +
session[sessionKey]);
}
errorMessage += "\rStack Trace:";
errorMessage += exception.StackTrace;
WriteEntry(errorMessage, entryType);
if (!QuietTypes.Contains(exception.GetType()))
SendExceptionEmail(errorMessage);
}
This is some VB code we use, it provides enougth info for us to diagnose most problems. Only downside with emailing errors like this is when there is a major failure you can end up with thousands of messages in your mailbox :(
Dim e As Exception
If System.Web.HttpContext.Current.Request.IsLocal Then Exit Sub
e = System.Web.HttpContext.Current.Server.GetLastError
If e IsNot Nothing Then
If TypeOf e Is HttpException Then
Dim he As HttpException = DirectCast(e, HttpException)
If he.GetHttpCode=404 Then
System.Web.HttpContext.Current.Server.ClearError()
Response.Redirect("/")
Exit Sub
End If
End If
MsgBody += "Exception: " & e.Message & vbCrLf & vbCrLf
MsgBody += e.ToString & vbCrLf & vbCrLf & vbCrLf
Else
MsgBody += "Unknown Error" & vbCrLf & vbCrLf & vbCrLf
End If
If System.Web.HttpContext.Current.Request.Url Is Nothing Then
MsgBody += "URL: ?" & vbCrLf & vbCrLf
Else
MsgBody += "URL: " & System.Web.HttpContext.Current.Request.Url.ToString & vbCrLf
If System.Web.HttpContext.Current.Request.RawUrl IsNot Nothing Then MsgBody += System.Web.HttpContext.Current.Request.RawUrl & vbCrLf
MsgBody += vbCrLf
End If
If System.Web.HttpContext.Current.Request.UrlReferrer Is Nothing Then
MsgBody += "Referer: <direct>" & vbCrLf & vbCrLf
Else
MsgBody += "Referer: " & System.Web.HttpContext.Current.Request.UrlReferrer.ToString() & vbCrLf & vbCrLf
End If
If User IsNot Nothing Then MsgBody += "User: " & User.Identity.Name & vbCrLf
MsgBody += "User-Agent: " & System.Web.HttpContext.Current.Request.UserAgent & vbCrLf
MsgBody += "User-IP: " & System.Web.HttpContext.Current.Request.UserHostAddress & vbCrLf
MsgBody += "Server: " & System.Environment.MachineName & vbCrLf
MsgBody += vbCrLf & "RequestType: " & System.Web.HttpContext.Current.Request.RequestType() & vbCrLf & vbCrLf
' dump request items
' QueryString, Form, Cookies, ServerVariables
MsgBody += "Querystring Variables ================" & vbCrLf
If Request.QueryString.Count > 0 Then
For Each key As String In Request.QueryString.Keys
MsgBody += key & " = " & Request.QueryString(key) & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
MsgBody += "Form Variables =======================" & vbCrLf
If Request.Form.Count > 0 Then
For Each key As String In Request.Form.Keys
MsgBody += key & " = " & Request.Form(key) & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
MsgBody += "Cookies ==============================" & vbCrLf
If Request.Cookies.Count > 0 Then
For Each key As String In Request.Cookies.Keys
MsgBody += key & " = " & Request.Cookies(key).Value & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
MsgBody += "ServerVariables ======================" & vbCrLf
If Request.ServerVariables.Count > 0 Then
For Each key As String In Request.ServerVariables.Keys
MsgBody += key & " = " & Request.ServerVariables(key) & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
' we send MsgBody via email using the System.Net.Mail.MailMessage & System.Net.Mail.SmtpClient classes
' we've handled the error
System.Web.HttpContext.Current.Server.ClearError()
' depending on the error we redirect to our homepage /default.aspx unless that is the faulting page then redirect to static /error.html
This is a classic sort of question, I suppose, but it seems that most people are interested in having the textbox cause a postback. I'm not. I just want the event to fire when a postback occurs.
I have created a webpart with a custom editorpart. The editorpart renders with a textbox and a button. Clicking the button causes a dialog to open. When the dialog is closed, it sets the value of the textbox via javascript and then does __doPostBack using the ClientID of the editorpart.
The postback happens, but the TextChanged event never fires, and I'm not sure if it's a problem with the way __doPostBack is invoked, or if it's because of the way I'm setting up the event handler, or something else. Here's what I think is the relevant portion of the code from the editorpart:
protected override void CreateChildControls()
{
_txtListUrl = new TextBox();
_txtListUrl.ID = "targetSPList";
_txtListUrl.Style.Add(HtmlTextWriterStyle.Width, "60%");
_txtListUrl.ToolTip = "Select List";
_txtListUrl.CssClass = "ms-input";
_txtListUrl.Attributes.Add("readOnly", "true");
_txtListUrl.Attributes.Add("onChange", "__doPostBack('" + this.ClientID + "', '');");
_txtListUrl.Text = this.ListString;
_btnListPicker = new HtmlInputButton();
_btnListPicker.Style.Add(HtmlTextWriterStyle.Width, "60%");
_btnListPicker.Attributes.Add("Title", "Select List");
_btnListPicker.ID = "browseListsSmtButton";
_btnListPicker.Attributes.Add("onClick", "mso_launchListSmtPicker()");
_btnListPicker.Value = "Select List";
this.AddConfigurationOption("News List", "Choose the list that serves as the data source.",
new Control[] { _txtListUrl, _btnListPicker });
if (this.ShowViewSelection)
{
_txtListUrl.TextChanged += new EventHandler(_txtListUrl_TextChanged);
_ddlViews = new DropDownList();
_ddlViews.ID = "_ddlViews";
this.AddConfigurationOption("View", _ddlViews);
}
}
protected override void OnPreRender(EventArgs e)
{
ScriptLink.Register(this.Page, "PickerTreeDialog.js", true);
string lastSelectedListId = string.Empty;
if (!this.WebId.Equals(Guid.Empty) && !this.ListId.Equals(Guid.Empty))
{
lastSelectedListId = SPHttpUtility.EcmaScriptStringLiteralEncode(
string.Format("SPList:{0}?SPWeb:{1}:", this.ListId.ToString(), this.WebId.ToString()));
}
string script = "\r\n var lastSelectedListSmtPickerId = '" + lastSelectedListId + "';"
+ "\r\n function mso_launchListSmtPicker(){"
+ "\r\n if (!document.getElementById) return;"
+ "\r\n"
+ "\r\n var listTextBox = document.getElementById('" + SPHttpUtility.EcmaScriptStringLiteralEncode(_txtListUrl.ClientID) + "');"
+ "\r\n if (listTextBox == null) return;"
+ "\r\n"
+ "\r\n var serverUrl = '" + SPHttpUtility.EcmaScriptStringLiteralEncode(SPContext.Current.Web.ServerRelativeUrl) + "';"
+ "\r\n"
+ "\r\n var callback = function(results) {"
+ "\r\n if (results == null || results[1] == null || results[2] == null) return;"
+ "\r\n"
+ "\r\n lastSelectedListSmtPickerId = results[0];"
+ "\r\n var listUrl = '';"
+ "\r\n if (listUrl.substring(listUrl.length-1) != '/') listUrl = listUrl + '/';"
+ "\r\n if (results[1].charAt(0) == '/') results[1] = results[1].substring(1);"
+ "\r\n listUrl = listUrl + results[1];"
+ "\r\n if (listUrl.substring(listUrl.length-1) != '/') listUrl = listUrl + '/';"
+ "\r\n if (results[2].charAt(0) == '/') results[2] = results[2].substring(1);"
+ "\r\n listUrl = listUrl + results[2];"
+ "\r\n listTextBox.value = listUrl;"
+ "\r\n __doPostBack('" + this.ClientID + "','');"
+ "\r\n }"
+ "\r\n LaunchPickerTreeDialog('CbqPickerSelectListTitle','CbqPickerSelectListText','websLists','', serverUrl, lastSelectedListSmtPickerId,'','','/_layouts/images/smt_icon.gif','', callback);"
+ "\r\n }";
this.Page.ClientScript.RegisterClientScriptBlock(typeof(ListPickerEditorPart), "mso_launchListSmtPicker", script, true);
if ((!string.IsNullOrEmpty(_txtListUrl.Text) && _ddlViews.Items.Count == 0) || _listSelectionChanged)
{
_ddlViews.Items.Clear();
if (!string.IsNullOrEmpty(_txtListUrl.Text))
{
using (SPWeb web = SPContext.Current.Site.OpenWeb(this.WebId))
{
foreach (SPView view in web.Lists[this.ListId].Views)
{
_ddlViews.Items.Add(new ListItem(view.Title, view.ID.ToString()));
}
}
_ddlViews.Enabled = _ddlViews.Items.Count > 0;
}
else
{
_ddlViews.Enabled = false;
}
}
base.OnPreRender(e);
}
void _txtListUrl_TextChanged(object sender, EventArgs e)
{
this.SetPropertiesFromChosenListString(_txtListUrl.Text);
_listSelectionChanged = true;
}
Any ideas?
Update: I forgot to mention these methods, which are called above:
protected virtual void AddConfigurationOption(string title, Control inputControl)
{
this.AddConfigurationOption(title, null, inputControl);
}
protected virtual void AddConfigurationOption(string title, string description, Control inputControl)
{
this.AddConfigurationOption(title, description, new List<Control>(new Control[] { inputControl }));
}
protected virtual void AddConfigurationOption(string title, string description, IEnumerable<Control> inputControls)
{
HtmlGenericControl divSectionHead = new HtmlGenericControl("div");
divSectionHead.Attributes.Add("class", "UserSectionHead");
this.Controls.Add(divSectionHead);
HtmlGenericControl labTitle = new HtmlGenericControl("label");
labTitle.InnerHtml = HttpUtility.HtmlEncode(title);
divSectionHead.Controls.Add(labTitle);
HtmlGenericControl divUserSectionBody = new HtmlGenericControl("div");
divUserSectionBody.Attributes.Add("class", "UserSectionBody");
this.Controls.Add(divUserSectionBody);
HtmlGenericControl divUserControlGroup = new HtmlGenericControl("div");
divUserControlGroup.Attributes.Add("class", "UserControlGroup");
divUserSectionBody.Controls.Add(divUserControlGroup);
if (!string.IsNullOrEmpty(description))
{
HtmlGenericControl spnDescription = new HtmlGenericControl("div");
spnDescription.InnerHtml = HttpUtility.HtmlEncode(description);
divUserControlGroup.Controls.Add(spnDescription);
}
foreach (Control inputControl in inputControls)
{
divUserControlGroup.Controls.Add(inputControl);
}
this.Controls.Add(divUserControlGroup);
HtmlGenericControl divUserDottedLine = new HtmlGenericControl("div");
divUserDottedLine.Attributes.Add("class", "UserDottedLine");
divUserDottedLine.Style.Add(HtmlTextWriterStyle.Width, "100%");
this.Controls.Add(divUserDottedLine);
}
It can help, if the class declaring the event handler (in your case the editorpart, I guess) implements System.Web.UI.INamingContainer. And do you add _txtListUrl to the Controls collection?
EDIT:
Make sure that the AutoPostBack property of _txtListUrl is set to true (_txtListUrl.AutoPostBack = true).
_txtListUrl.Attributes.Add("onChange" might interfere with the event handler.
TextChanged is invoked only, when the text box looses the focus.
I want dynamical add HTML on my div.
I do this with:
newsAllScroller.InnerHtml = newsAllScroller.InnerHtml + "<br><center><b>";
List<DAL.News> newsList = DAL.NewsHandler.GetAllNews();
foreach (DAL.News n in newsList)
{
newsAllScroller.InnerHtml = newsAllScroller.InnerHtml + "<br>" + n.Betreff + " - ("
+ "<asp:HyperLink ID=\"news"+n.NewsID+"\" runat=\"server\" NavigateUrl=\"~/News.aspx?id=" + n.NewsID + "\""
+ " CssClass=\"newsLink\">"
+ "..."
+ "</asp:HyperLink>"
+ ")";
}
newsAllScroller.InnerHtml = newsAllScroller.InnerHtml + "</center></b>";
The HyperLink is not working (you cannot click it).
When I copy the hyperlink from the browser-source-code into an aspx-page it works, so it seems the syntax is all correct - but it doasn't work via code, why?
You cannot add server side control to HTML and think of it to behave normally, you would have to modify your code to
newsAllScroller.InnerHtml = newsAllScroller.InnerHtml + "<br>" + n.Betreff + " - ("
+ "<a href ="/News.aspx?id=" + n.NewsID + "\""
+ " class=\"newsLink\">"
+ "... </a>"
+ ")";
Because the aspx page is parsed only once before the output is sent to the browser. You can't print/output something and expect it to be parsed once more.
You should use a Repeater instead of appending text to InnerHtml. Something like this:
<asp:Repeater ID="myRepeater" runat="server" OnItemDataBound="myRepeater_ItemDataBound">
<ItemTemplate>
<br/><asp:Literal ID="myText" runat="server"/> - (<asp:HyperLink ID="myLink" runat="server" CssClass="newsLink" Text="..."/>)
</ItemTemplate>
</asp:Repeater>
...and then in code-behind:
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
myRepeater.DataSource = DAL.NewsHandler.GetAllNews();
myRepeater.DataBind();
}
}
void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
var myText = e.Item.FindControl("myText") as Literal;
var myLink = e.Item.FindControl("myLink") as HyperLink;
var news = e.Item.DataItem as DAL.News;
if (myText != null && myLink != null && news != null)
{
myText.Text = news.Betreff;
myLink.NavigateUrl = "~/News.aspx?id=" + news.NewsID;
}
}
}
I haven't tried the code myself but it should point you in the right direction. Check out the Repeater documentation for more information and examples.