Change id of elements in ContentPlaceHolder - asp.net

I use masterpage in asp.net web form, I use span to display message to users
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<div class="col-md-10 col-sm-10">
<span id="spnMessage" class="btnText" runat="server"></span>
</div>
</asp:Content>
and code is:
spnMessage.InnerText = "Add record successfully ";
but in runtime id of span change to "ContentPlaceHolder2_spnMessage" and my code does not work. What should I do?

Change the span into a Literal. Then there will be no more issues with ID conflicts.
<asp:Literal ID="spnMessage" runat="server"></asp:Literal>
Then accessing the Literal from code behind will always work.
spnMessage.Text = "Add record successfully ";
Or if you need to use the <span> element for CSS purposes, you can still wrap the Literal with it.
<span><asp:Literal ID="spnMessage" runat="server"></asp:Literal></span>
You could also use a aspnet Label.
A label will generate it's own <div> tag in HTML.
<asp:Label ID="spnMessage" runat="server" Text="Add record successfully"></asp:Label>
Will become
<div>Add record successfully</div>

Related

why it says there are not my text boxes

i wrote below code . but i do not know why i get error. but every thing seems ok.
it says there are not my text boxes in context. but there are .
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<form id="form1" runat="server">
<asp:TextBox ID="address" runat="server"/>
<div class="form1">
<label for="fname">
<span>name:</span>
<asp:TextBox ID="fname" runat="server"/>
</label>
<label for="lname">
<span>lname: </span>
<asp:TextBox ID="lname" name="lname" runat="server" />
</label>
.
.
.
</div>
protected void send2_Click(object sender, EventArgs e)
{
tbl_register tbl = new tbl_register();
tbl.firstname = fname.Text; // The name 'fname' does not exist in the current context
tbl.lastname = lname.Text; // The name 'lname'does not exist in the current context
tbl.address = address1.Text; //..
tbl.phone = phone.Text; //..
tbl.email = email3.Text; //..
db.tbl_registers.InsertOnSubmit(tbl);
db.SubmitChanges();
}
The textboxes as coded are children of the label. I do not code my lables in that way. In order to use controls that are child controls you must use Control.FindControl, in this case fname.FindControl("fname"). I would not name controls the same as other controls. You can also close the label tag such that it does not enclose those controls, and then the control can be referenced via the name.
the line
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
suggests that this is a webform that uses a MasterPage.
inside the content place holder you have a form declaration that runs at server:
<form id="form1" runat="server">
however, on your MasterPage.master you already have a form that runs at server that wraps the content placeholder.
asp.net does not allow 2 nested forms to both run at server.

Why can not use <%=...%> in the ListView

All, Generally .If we want to output a variable in a page which defined in the code-behind class file of page . We could set the variable with public or protect visibility. and in the front page we can use it like below.
<%=VariableName%>.
But I don't know why can't use it in the ListView. Please help to review my code.
In the front page
<div id="divIssuedListContainer" class="myIssuedList">
<asp:ListView id="listShower" runat="server">
<LayoutTemplate>
<div id="divIssuedListHeadTitle">
<div id="divIssuedListTitleIco">
<img alt="" src="ico/IssuedCap.png" />
</div>
<div id="divIssuedListTitleName">
<span>ISSUED</span><span>TRADE NAMES</span><span>/LICENSES</span>
</div>
<div id="divIssuedListItemNumber">
<span>
<%=iListNumber%></span>
</div>
</div>
<div style="clear:both"></div>
<div id="divIssuedListBody">
<ul>
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</ul>
</div>
</LayoutTemplate>
<ItemTemplate>
<li>
<table>
<tr>
<td>
<img alt="" src="" />
</td>
<td>
<div>
<span>
<%# Eval("altID") %>
-
<%# Eval("englishTradeName") %></span></div>
<div>
<span>Expired Date:<%# Eval("expDate") %></span>
</div>
</td>
</tr>
</table>
</li>
</ItemTemplate>
</asp:ListView>
In the code-behind of page
public partial class _Default : System.Web.UI.Page
{
protected int iListNumber = 0;
protected void Page_Load(object sender, EventArgs e)
{
List<SimpleCapModel> DataSourceList = TestDataHelper.GetMyIssuedList();
listShower.DataSource = DataSourceList;
iListNumber = DataSourceList.Count();
listShower.DataBind();
}
}
I got an error page said :
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Source Error:
Line 19: listShower.DataSource = DataSourceList;
Line 20: iListNumber = DataSourceList.Count();
Line 21: listShower.DataBind();//this line cause error.
Line 22: }
Line 23: }
And If I use the expression <%#iListNumber%>. The error is gone, but I got a empty value instead of the number of the list. please review below rendered result html :
<div id="divIssuedListItemNumber">
<span> </span>
</div>
I didn't know whether I missed something ? If I did .Please help to let me know it.thanks.
You need to use <%#iListNumber %> because you are using data-binding the ListView, otherwise you'll get the exception (see: http://support.microsoft.com/kb/976112 for more on inline expressions).
Try using <%#iListNumber.ToString %> and see if that makes a difference.
UPDATE:
The problem appears to be that your inline-expression is in the LayoutTemplate, where data-binding [apparently] won't work without either handling the OnLayoutCreated event, or extending the ListView.
See either of the following for examples of how to extend the ListView:
http://www.codeproject.com/Articles/42962/Databind-Expression-in-ListView-LayoutTemplate
http://forums.asp.net/p/1201992/3319344.aspx#3319344
Given the error you're receiving, it basically means this: you can't just randomly throw .NET tags in databound controls.
The solution is to, instead, throw that random text in a .NET control, like this: <asp:Literal Runat="server" Text="<%# iListNumber %>" />
When you put a .NET codeblock in code, it dynamically has to build a control placeholder for it. It's a little tricky. But if you wrap all your custom tags up in a control, then just that one property gets databound and the databound block remains "clean" if that makes sense.

How is my page creating two different types of checkbox?

Got a really weird thing happening on my page. I have some checkbox controls and some of them are rendering like this..
<span confirmmodified="true" class="aspNetDisabled"><input type="checkbox" disabled="disabled" name="ctl00$FormContents$TrackerDetails$OutOfScopeUSQS" id="ctl00_FormContents_TrackerDetails_OutOfScopeUSQS"><label for="ctl00_FormContents_TrackerDetails_OutOfScopeUSQS">Out of scope USQS</label></span>
But some of them are rendering like this...
<input type="checkbox" name="ctl00$FormContents$TrackerDetails$OutOfScopeSQA" id="ctl00_FormContents_TrackerDetails_OutOfScopeSQA"><label for="ctl00_FormContents_TrackerDetails_OutOfScopeSQA">Out of scope USQS</label>
See, no span? Cant work out what is going on I have looked at the page and control and doesnt seem like anything different is happening...
UPDATE: [this is the markup]
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AuditStateTracker.ascx.cs"
Inherits="Dashboard.controls.AuditStateTracker" %>
<div class="grid_12 alpha">
<h2><asp:Literal runat="server" Text="<%$ Resources:LocalisedText, TrackerMigration%>" /></h2>
</div>
<div class="grid_1">
<asp:CheckBox ID="OutOfScopeUSQS" runat="server" Text="<%$ Resources:LocalisedText, OutOfScopeUSQS %>" />
</div>
<div class="grid_1" runat="server" ID="divOutOfScopeSQA">
<asp:CheckBox ID="OutOfScopeSQA" runat="server" Text="<%$ Resources:LocalisedText, OutOfScopeUSQS %>" />
</div>
<div class="grid_1">
<asp:CheckBox ID="OutOfScopeRS" runat="server" Text="<%$ Resources:LocalisedText, OutOfScopeRS %>" />
</div>
<div class="grid_1" runat="server" ID="divRingFencedSQA">
<asp:CheckBox ID="RingFencedSQA" runat="server" Text="<%$ Resources:LocalisedText, RingFencedSQA %>" />
</div>
<div class="grid_1">
<asp:CheckBox ID="RingFencedRS" runat="server" Text="<%$ Resources:LocalisedText, RingFencedRS %>" />
</div>
<div class="grid_1" runat="server" ID="divBusinessCase">
<asp:CheckBox ID="BusinessCase" runat="server" Text="<%$ Resources:LocalisedText, BusinessCase %>" />
</div>
<div class="grid_1" runat="server" ID="divDelisted" visible="false">
<asp:CheckBox ID="Delisted" runat="server" Text="<%$ Resources:LocalisedText, Delisted %>" />
</div>
The first checkbox is disabled, the second one isn't; that's how asp.net renders disabled checkboxes.
It's throwing that span on there so asp.net can decorate it with the css class aspNetDisabled. This would allow you to (optionally) style disabled controls differently.
Incidentally, this disabled class is actually configurable.
In earlier versions of ASP.NET Microsoft used to render the disabled = "disabled"attribute for your controls. However, since the HTML 4.01 specification, the disabled attribute is not valid anymore for each type of web control. It is still valid for input, but not anymore for span.
So what they've done is add a style class (in CSS) which is set to controls when they are disabled. This is also the case with any controls in a diabled control. By default, this style class is called `aspNetDisabled'.
You can actually use a different name for this class, but not for individual controls. The name of this style class can only be set as a static property on the root class WebControl, for instance at application start in your global.asax.cs.
protected void Application_Start(object sender, EventArgs e)
{
WebControl.DisabledCssClass = "disabled";
}
More annoying is that for checkboxes, ASP.NET renders a span around you checkbox with the defined style class on it.
<span disabled="disabled">
<input id="ctl00_UsecaseContent_ctl01_ctl01_bCVbox" type="checkbox" name="ctl00$UsecaseContent$ctl01$ctl01$bCVbox" checked="checked">
</span>
When you are using e.g. Bootstrap as your UI framework, and on top of that a checkbox specific framework, such as https://github.com/flatlogic/awesome-bootstrap-checkbox, this additional span can actually break the structure of your HTML checkbox control hierarchy.

asp.net dynamic forms question

I'm trying to figure out a way to create a page that can be used for generic forms. What i had in mind was someone here at our office would use the obout edit to create html that would look like a form. This html would be saved to a database. When the user wanted to fill out the form and mail it, they would click on the correct form retrieval and this html would be put into a label control. So now the page has a label control on it with some html as the text of the label. The user could type in the values that they wanted. So the html might look something like this:
<p style="margin: 0px; text-align: center;">
Quarterly Report of Employees Serverd</p>
<br />
<br />
Employee:
<input type="text" style="width: 300px; height: 22px;" />
<br />
<br />
Address:
<input type="text" style="width: 300px; height: 22px;" />
<br />
<br />
<br />
The user would type in the input type="text" a value of say John Smith and then type into the address input type as well.
Now I want to grab all this html and mail it off. I know how to do the mailing portion, but the grabbing the html I'm not getting. I can grab the html in the label, but the text that that user typed in is not included in that text. So how do I get that html and the text the user typed in. Any ideas.
thanks
shannon
You need to encode the html to store them securely.
Use literal control instead of label or text controls.
Check this link for the first option.
Thanks :)
and you can use a way like this :
<input id="textField" type="text" runat="server"/>
C# - Code Behind
Mail.Send(textField.Value);
and don't forget to use ValidateRequest="false" in the header section of asp.net..
:)
You can iterate through the Request items to get the submitted values. If you want to send of an email which substitutes the entered values for the HTML input fields, you'll have to parse out the form HTML to find your input fields:
<input type="text" id="firstName" name="firstName"
style="width: 300px; height: 22px;" />
And then replace it with
Request.Form["firstName"]
Notice that the input fields will need identifiers so you can retrieve them from the HTTP request.
Hope this helps!
For one thing, you're really going to want to get a little more information into your html - at the very least some name attributes on the form elements:
Employee: <input type="text" name="employee" />
This way, you could create an aspx page like:
<%# Page language="C#"
autoeventwireup="true"
codebehind="DynamicForm.aspx.cs"
inherits="TempWebApp.DynamicForm" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal id="m_HtmlForm" runat="server"></asp:Literal>
<asp:Button id="m_SubmitForm"
onclick="SubmitForm_OnClick"
runat="server"
text="Submit" />
</div>
</form>
</body>
</html>
Then in your code you read your html from the database into the .Text of the literal control:
using System;
using System.Web.UI;
namespace TempWebApp
{
public partial class DynamicForm : Page
{
protected void Page_Load(object sender, EventArgs e)
{
m_HtmlForm.Text = getFormData();
}
protected void SubmitForm_OnClick(object sender, EventArgs e)
{
// Just showing we've picked up the form data.
// You'll also see ViewState and others in here.
foreach (string key in Request.Form.AllKeys)
{
m_HtmlForm.Text += string.Format("<br />Key: <b>{0}</b><br />Value:<br />{1}<br />", key, Request.Form[key]);
}
}
private string getFormData()
{
// Excluded for brevity
}
}
}
Obviously, in your button/postback handler, you would need to ensure you have the original HTML from the database, and then either modify the input elements to add a text attribute to them with the value, or more likely, replace them with the actual values - otherwise you'll have to do lots of additional parsing of the form if your users start saving forms with radio buttons, check boxes, select lists, etc.

ASP.NET catching controls from html generated from the database

I have a set of websites that basically do the exact same thing in terms of functionality, the only thing that varies is the css and how the html is laid out.
Is there a way to generate the html from a database (ie retreiving the html from a table) and then catching the controls (like buttons, textboxes etc) from the code behind?
UPDATE:
Here is an example of what I want to acheive:
<html>
<div id="generatedContent" runat="server">
<!-- the following content has been generated from the database on the page load event -->
<div>
This is a textbox <input id="tb1" runat="server" type="text" />
This is a button <input type="submit" id="btn1" runat="server" value="My Button" />
</div>
</div>
</html>
This is the code behind
var tb1 = new HtmlControls.HtmlInputText();
tb1 = FindControl("tb1");
var btn1 = new New HtmlControls.HtmlInputSubmit();
btn1 = FindControl("btn1");
Now obviously since the html has been generated from the database (ie after the page has already been initialised) the FindControl method will return null.
For static HTML content, you can easily add your content to your form by using LiteralControl like that :
Page.Controls.Add(new LiteralControl("<b>content from db</b>"));
EDIT : Your code-behind code (FindControl) should work if you put them in a form tag with runat=server attribute. But beware, your content should be added in every postback. Also you can get the values of your form elements by Request["FormElementId"].

Resources