Repeater does not show data - c#

As posted earlier , Here is my HTML :
<%# Page Title="" Language="C#" MasterPageFile="~/VendorMaster.master" AutoEventWireup="true" CodeFile="PastOrders.aspx.cs" Inherits="PastOrders" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<br />
<asp:Repeater ID="rptr" runat="server">
<HeaderTemplate>
<div class="col-lg-4 col-md-4 col-sm-4 mb">
<a href="VendorProfile.aspx">
<div class="twitter-panel pn">
<i class="fa fa-twitter fa-4x"></i>
</HeaderTemplate>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Name") %>
</ItemTemplate>
<FooterTemplate>
</div>
</a>
</FooterTemplate>
</asp:Repeater>
</asp:Content>
C# :
public partial class PastOrders : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["vendor"] != null)
{
if (!IsPostBack)
{
ArrayList values = new ArrayList();
values.Add(new Testing
{
Name = "Caterer"
});
values.Add(new Testing
{
Name = "Florist"
});
values.Add(new Testing
{
Name = "Cab Services"
});
rptr.DataSource = values;
rptr.DataBind();
}
}
else
{
Response.Redirect("VendorLogin.aspx");
}
}
public class Testing
{
public string Name { get; set; }
}
}
Now i want to generate 3 separate divs, with the Names on them as : "Caterer","Florist","Cab Services",etc.
Instead it is only generating one div with all the 3 names inside it .
I tried formatting it with the Header Template and the Footer Template where i put the parent divs and the anchor tag in the Header Template and the closing of the same in the Footer Template . Bt it doesn't produce the expected result still.

Now you do bind data, but you do not access your data within your repater. Change it to
<form id="form1" runat="server">
<asp:Repeater ID="rptr" runat="server" >
<ItemTemplate>
<div class="divStyle" id="divStyle">
<%# DataBinder.Eval(Container.DataItem, "Name") %>
</div>
</ItemTemplate>
</asp:Repeater>
</form>
and it should work!

Related

Insert My .NET Control In Template

I am new to ASP.NET. As a follow up question from THIS POST I have the following .Net Control in Ektron that I would like to display in my webpage template.
Control:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Gallery.ascx.cs" Inherits="Source_Controls_Alumni_Gallery" %>
<asp:ListView ID="uxPhotoGallery" runat="server" ItemPlaceholderID="itemPlaceholder">
<LayoutTemplate>
<ul>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<%--
I'm mixing up two different ways of referencing the incoming data. One is by casting
the DataItem to the incoming type, which gives you intellisense access to the properties.
The other is more of a dictionary approach in which you have to type out the property name
as a string.
I really like the casting approach, but it's mega-wordy.
--%>
<a href="<%#((Ektron.Custom.ViewModels.PressPhotoViewModel)Container.DataItem).ImageUrl %>">
<img src="<%#((Ektron.Custom.ViewModels.PressPhotoViewModel)Container.DataItem).ImageUrl %>" alt="<%#Eval("Description") %>" />
<div><%#Eval("Description") %></div>
</a>
</li>
</ItemTemplate>
</asp:ListView>
and code behind:
using Ektron.Custom.SmartForms;
using System;
using System.Linq;
public partial class Source_Controls_Alumni_Gallery : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
var pressPhotoManager = new PressPhotoManager();
// Whichever folder Id...
var photos = pressPhotoManager.GetList(75);
if (photos != null && photos.Any())
{
uxPhotoGallery.DataSource = photos;
uxPhotoGallery.DataBind();
}
}
}
I would like to insert the control into this template:
<%# Page Title="" Language="C#" MasterPageFile="~/Source/Masterpages/MainMaster.master" AutoEventWireup="true" CodeFile="AlumniJobOpenings.aspx.cs" Inherits="Source_Templates_AlumniJobOpenings" %>
<%# Register Src="~/Source/Controls/SubHeader.ascx" TagPrefix="uc1" TagName="SubHeader" %>
<%# Register Src="~/Source/Controls/Shared/PrimarySection.ascx" TagPrefix="uc1" TagName="PrimarySection" %>
<%# Register Src="~/Source/Controls/JoinUs/StaffAndParalegals/SPOpenings.ascx" TagPrefix="uc1" TagName="SPOpenings" %>
<%# Register Src="~/Source/Controls/JoinUs/StaffAndParalegals/SPFilters.ascx" TagPrefix="uc1" TagName="SPFilters" %>
<%# Register Src="~/Source/Controls/Shared/RelatedContentModules.ascx" TagPrefix="uc1" TagName="RelatedContentModules" %>
<%# Register Src="~/Source/Controls/JoinUs/StaffAndParalegals/SPContactDetails.ascx" TagPrefix="uc1" TagName="SPContactDetails" %>
<%# Register Src="~/Source/Controls/Shared/TextImageAssetBlockModules.ascx" TagPrefix="uc1" TagName="TextImageAssetBlockModules" %>
<%# Register Src="~/Source/Controls/Shared/TextLinkBlockControl.ascx" TagPrefix="uc1" TagName="TextLinkBlockControl" %>
<%# Register TagPrefix="sp" TagName="Spinner" Src="~/Source/Controls/Alumni/Gallery.ascx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<uc1:SubHeader runat="server" ID="SubHeader" />
<div class="container non-responsive">
<div class="row">
<div class="col-sm-8 alpha">
<uc1:PrimarySection runat="server" ID="PrimarySection" />
<div class="primary">
<div class="container non-responsive">
<div class="row">
<div class="col-sm-8 alpha">
<div class="primary">
IMAGE GALLERY LIST SHOULD BE INSERTED HERE.
</div>
</div>
<div class="col-sm-4 beta">
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-4 beta">
<uc1:SPContactDetails runat="server" ID="SPContactDetails" />
<uc1:SPFilters runat="server" ID="SPFilters" Heading="Staff and Paralegal Openings" Text="Select an office below to learn more about current opportunities" />
<uc1:RelatedContentModules runat="server" ID="RelatedContentModules" />
<uc1:TextLinkBlockControl runat="server" ID="TextLinkBlockControl" />
<uc1:TextImageAssetBlockModules runat="server" ID="TextImageAssetBlockModules" />
</div>
</div>
</div>
</asp:Content>
Here's your line from the top:
<%# Register TagPrefix="sp" TagName="Spinner" Src="~/Source/Controls/Alumni/Gallery.ascx" %>
And a similar line used to register another control in the same page:
<%# Register Src="~/Source/Controls/SubHeader.ascx" TagPrefix="uc1" TagName="SubHeader" %>
Now, take a look at the control placement for the pre-existing item referenced above.
<uc1:SubHeader runat="server" ID="SubHeader" />
What you'll find is that the placement tag is made up of configured properties in the <%# Register ... %> line. Specifically, the TagPrefix and TagName values. You'll use those values to set up your own control placement, following this format:
<TagPrefix:TagName runat="server" ID="SomeUniqueID" [optional parameters] />
So, in the case of your control, you've set TagPrefix="sp" and TagName="Spinner". So your control placement will look like this:
<sp:Spinner runat="server" ID="uxAlumniSpinner" />
(ID is an example)
From your control code, you don't have any parameters configured, so the above would work fine. But you could provide at least one parameter, and probably should in order to make the control more reusable.
For example, you've got a hard-coded value of 75 in your method call. I assume that's pointing to an Ektron Folder, Taxonomy, or Collection. Regardless, it's some container ID. You might want to use this control in multiple places with different sources for the data - different container IDs. The way you've set this up, you'll have to make a new control every time just to update that value.
So if we add a public property to your control, so that the code-behind looks like this:
using Ektron.Custom.SmartForms;
using System;
using System.Linq;
public partial class Source_Controls_Alumni_Gallery : System.Web.UI.UserControl
{
// Added Property
private long _containerId = 0;
public long ContainerID {
get { return _containerId; }
set { _containerId = value; }
}
/////////
protected void Page_Load(object sender, EventArgs e)
{
// Added inverted conditional to escape method
// if the _containerId is invalid.
if(_containerId <= 0) return;
///////////
var pressPhotoManager = new PressPhotoManager();
// Whichever folder Id...
var photos = pressPhotoManager.GetList(_containerId);
if (photos != null && photos.Any())
{
uxPhotoGallery.DataSource = photos;
uxPhotoGallery.DataBind();
}
}
}
Then you could specify the container ID whenever and wherever you place the control. Like so:
<sp:Spinner runat="server" ID="uxAlumniSpinner" ContainerID="75" />
Making your final in-template markup:
<%# Register Src="~/Source/Controls/JoinUs/StaffAndParalegals/SPContactDetails.ascx" TagPrefix="uc1" TagName="SPContactDetails" %>
<%# Register Src="~/Source/Controls/Shared/TextImageAssetBlockModules.ascx" TagPrefix="uc1" TagName="TextImageAssetBlockModules" %>
<%# Register Src="~/Source/Controls/Shared/TextLinkBlockControl.ascx" TagPrefix="uc1" TagName="TextLinkBlockControl" %>
<%# Register TagPrefix="sp" TagName="Spinner" Src="~/Source/Controls/Alumni/Gallery.ascx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<uc1:SubHeader runat="server" ID="SubHeader" />
<div class="container non-responsive">
<div class="row">
<div class="col-sm-8 alpha">
<uc1:PrimarySection runat="server" ID="PrimarySection" />
<div class="primary">
<div class="container non-responsive">
<div class="row">
<div class="col-sm-8 alpha">
<div class="primary">
<sp:Spinner runat="server" ID="uxAlumniSpinner" ContainerID="75" />
</div>
</div>
<div class="col-sm-4 beta">
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-4 beta">
<uc1:SPContactDetails runat="server" ID="SPContactDetails" />
<uc1:SPFilters runat="server" ID="SPFilters" Heading="Staff and Paralegal Openings" Text="Select an office below to learn more about current opportunities" />
<uc1:RelatedContentModules runat="server" ID="RelatedContentModules" />
<uc1:TextLinkBlockControl runat="server" ID="TextLinkBlockControl" />
<uc1:TextImageAssetBlockModules runat="server" ID="TextImageAssetBlockModules" />
</div>
</div>
</div>
</asp:Content>

ASP how to find controls of type on a child page of a master page

I have a master page master.page.
And I have a child page default.aspx that inheirts master.
How do I preform the following and actually find controls. In the below code I never find my panels.
codebehind - content-page
foreach (Panel pnl in this.Page.Controls.OfType<Panel>())
{
if (pnl.ID.ToUpper() == texthi.ToUpper().Replace(" ", ""))
{
pnl.Visible = true;
}
else
{
pnl.Visible = false;
}
}
aspx - content-page
<%# Page Title="" Language="C#" MasterPageFile="~/secure/Wizard.master" AutoEventWireup="true"
CodeFile="AddWarranty.aspx.cs" Inherits="secure_Warranties_AddWarranty" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder_NavigationPanel"
runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:ScriptManager runat="server" ID="sm1">
</asp:ScriptManager>
<div id="header">
<p id="layoutdims">
</p>
</div>
<div class="colmask leftmenu">
<div class="colleft">
<div class="col1">
<asp:Panel runat="server" ID="VehicleInformation" Visible="true">
<legend>VEHICLE INFORMATION</legend>
</asp:Panel>
<asp:Panel runat="server" ID="CustomerInformation" Visible="false">
<legend>CUSTOMER INFORMATION</legend>
</asp:Panel>
</div>
The reason is that Enumerable.TypeOf does not look recursivelsy into child controls but only the top-container. Since you're using it on the page's ControlCollection you'll find only panels which are sitting on the top of the page. But your panels are inside of other divs.
Make the parent div(with class="col1") runat=server(or use Panel) and access it in codebehind:
foreach (Panel pnl in div.Controls.OfType<Panel>())
{
// ...
}

Changing the text of a hyperlink in asp.net on click?

I am trying to change the text of my hyperlink after the user has clicked it. Here is the hyperlink:
<asp:hyperlink id="OpenClose" runat="server" onclick="OpenClose_Click" AutoPostBack="true">Close</asp:hyperlink>
And here is my code behind:
protected void Page_Load(object sender, EventArgs e)
{
OpenClose.Attributes.Add("onclick", "OpenClose_Click");
}
protected void OpenClose_Click(object sender, EventArgs e)
{
if (OpenClose.Text == "Close")
OpenClose.Text = "Open";
else
OpenClose.Text = "Close";
}
The problem is that it does not seem to see the function OpenClose_Click. I am not sure why. Is there another method to do this or am I missing something?
EDIT
Here is the entire aspx code
<%# Page Title="" Language="C#" MasterPageFile="../MasterPageLite.master" AutoEventWireup="true" CodeFile="testPageLoad2.aspx.cs" Inherits="BuilderPages_testPageLoad2" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<div class="left_side">
<form id="form1" runat="server">
This is the second test page I am making. Practice collapse and expand panels!
<div class="msg_list">
<h3 class="msg_head">Header-1</h3>
<div class="msg_body">
Collapse this panel!!
<asp:button runat="server" text="Can you see me?" />
</div>
<h3 class="msg_head">Header-2</h3>
<div class="msg_body">
Congratulations you opened the panel!!
</div>
<h3 class="msg_head">Header-3</h3>
<div class="msg_body">
The third panel has been opened!!
</div>
</div>
</form>
</div>
<div class="right_side">
<div class="lBorder">
<asp:Panel ID="OpenClosePanel" runat="server"></asp:Panel>
<asp:HyperLink id="OpenClose" runat="server" AutoPostBack="true" style="cursor:pointer; text-decoration:underline;">Show/Hide</asp:HyperLink>
</div>
<div class="rscontent">
<p>
Lorem ipsum...
</p>
<p>
Nulla...
</p>
<p>
Vivamus...
</p>
<p>
Phasellus...
</p>
<p>
Aenean...
</p>
</div>
</div>
</asp:Content>
You should use a LinkButton instead of a HyperLink control, like this:
Markup:
<asp:LinkButton id="OpenClose"
runat="server"
OnClick="OpenClose_Click"
AutoPostBack="true"
Text="Close"></asp:LinkButton>
Code-Behind:
protected void OpenClose_Click(object sender, EventArgs e)
{
if (OpenClose.Text == "Close")
{
OpenClose.Text = "Open";
}
else
{
OpenClose.Text = "Close";
}
}
The LinkButton class derives from the Button class thus it has similar events to a button, which is the effect you want, but it renders like a hyperlink.
<asp:hyperlink ... is not a valid type of control since .NET is case sensitive. Try changing it to:
<asp:HyperLink ...
I would also get rid of the code in your page load event.

Getting a string in code-behind containing the selections in a multi-select listbox?

What I want to do is take all of the selected items from a milti-select listbox and put them in a comma separated string, so I can store it in a table. I've searched and found code, but for some reason the qualifier is never found to be "true". It sees every selected item as "false". Am I processing this in the wrong order?
Here's my ASP section (cut because it's a HUGE file, but this is the important stuff):
<%# Page Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PBR.WebForm1" MaintainScrollPositionOnPostback="true"%>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AJAXControls" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<link rel="stylesheet" href="Styles/ui.all.css" type="text/css" media="screen" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server" >
<asp:ScriptManager ID="ScriptManager2" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanelX" runat="server" UpdateMode="Conditional" Height="390px"
Width="900px" BorderStyle="Groove" BorderWidth="2px">
<ContentTemplate>
<AJAXControls:TabContainer runat="server" ID="tabContainer" Height="373" Width="900" >
<AJAXControls:TabPanel ID="secondTab" HeaderText="Tracking Page 2" runat="server">
<ContentTemplate>
<div style="border:1px solid blue;">
<asp:Panel ID="Panel2" runat="server" Height="40px" style="margin-left: 19px"
Width="860px">
<table>
<tr>
<td width="170">System/Document Change:</td>
<td width="30"><asp:ListBox id="ddlSysDocChg" runat="server" Width="90px" Rows="2" SelectionMode="Multiple"></asp:ListBox></td>
<td width="40"></td>
<td width="200">System/Document Change Completed:</td>
<td width="20"><asp:CheckBox ID="chkSysDocChg" runat="server" Text=" " AutoPostBack="true" /></td>
</tr>
</table>
</asp:Panel>
</div>
<p></p>
<div>
</div>
</ContentTemplate>
</AJAXControls:TabPanel>
</AJAXControls:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Button ID="btnSubmit" Text="Submit" OnClick="btnSubmit_OnClick"
runat="server" />
</div>
</asp:Content>
In my code-behind, I have this (as you can see, I've tried it 2 different ways and I believe I found both methods on this very website):
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
// Read the selected items from the listbox
//string SQLCode = "";
var selectedQuery = ddlSysDocChg.Items.Cast<ListItem>().Where(item => item.Selected);
string SQLCode = String.Join(",", selectedQuery).TrimEnd();
//foreach (ListItem listitem in ddlSysDocChg.Items)
// {
// if (listitem.Selected == true)
// {
// SQLCode = SQLCode + ", " + listitem;
// }
// }
}
Can anyone tell me why it always tells me there's nothing selected?
EDIT:
This is what's in my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(str))
// Check to see which tabs should be active
LoadTabPages();
{
try
{
string strSQL = "SELECT ComboValue, ComboText FROM dbo.tblComboBoxes WHERE ComboName = 'ddlSysDocChg' ORDER BY ComboText ASC;";
SqlDataAdapter adapter = new SqlDataAdapter(strSQL, str);
DataSet DailyRun = new DataSet();
adapter.Fill(DailyRun);
ddlSysDocChg.DataSource = DailyRun;
ddlSysDocChg.DataTextField = "ComboText";
ddlSysDocChg.DataValueField = "ComboValue";
ddlSysDocChg.DataBind();
foreach (ListItem item in ddlSysDocChg.Items)
{
item.Attributes.Add("Title", item.Text);
}
// Insert a blank row into the DropDownLists so there is no default name
ddlSysDocChg.Items.Insert(0, new ListItem("", ""));
}
catch (Exception ex)
{
// Handle the error
Console.WriteLine("Making Call to " + ex + "");
}
}
}
I think it's because your list is in an updatepanel whose postback is 'Conditional', and the button is 'outside' the updatepanel.
Try putting it 'inside' the update panel as in this tutorial:
http://msdn.microsoft.com/en-us/library/Bb399001(v=VS.100).aspx
Or alternatively, specify the button as a 'Trigger' as in the same tutorial.
Do you databind the ListBox also postbacks? Check the IsPostBack property:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack) DataBindListBox();
}

How do I allow HTML tags to be submitted in a textbox in asp.net?

First, I want to let everyone know that I am using an aspx engine not a Razor engine.
I have a table within a form. One of my textbox contains html tags like
</br>Phone: </br> 814-888-9999 </br> Email: </br> aaa#gmail.com.
When I go to build it it it gives me an error that says:
A potentially dangerous Request.Form value was detected from the client (QuestionAnswer="...ics Phone:<br/>814-888-9999<br...").
I tried the validation request="false" but it did not work.
I am sorry I didn't add my html code for you to look at so far. I am pulling some question up where I can edit it, if need be.
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
EditFreqQuestionsUser
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$("#freqQuestionsUserUpdateButton").click(function () {
$("#updateFreqQuestionsUser").submit();
});
});
</script>
<h2>Edit Freq Questions User </h2>
<%Administrator.AdminProductionServices.FreqQuestionsUser freqQuestionsUser = ViewBag.freqQuestionsUser != null ? ViewBag.freqQuestionsUser : new Administrator.AdminProductionServices.FreqQuestionsUser(); %>
<%List<string> UserRoleList = Session["UserRoles"] != null ? (List<string>)Session["UserRoles"] : new List<string>(); %>
<form id="updateFreqQuestionsUser" action="<%=Url.Action("SaveFreqQuestionsUser","Prod")%>" method="post" onsubmit+>
<table>
<tr>
<td colspan="3" class="tableHeader">Freq Questions User Details <input type ="hidden" value="<%=freqQuestionsUser.freqQuestionsUserId%>" name="freqQuestionsUserId"/> </td>
</tr>
<tr>
<td colspan="2" class="label">Question Description:</td>
<td class="content">
<input type="text" maxlength="2000" name="QuestionDescription" value=" <%=freqQuestionsUser.questionDescription%>" />
</td>
</tr>
<tr>
<td colspan="2" class="label">QuestionAnswer:</td>
<td class="content">
<input type="text" maxlength="2000" name="QuestionAnswer" value="<%=freqQuestionsUser.questionAnswer%>" />
</td>
</tr>
<tr>
<td colspan="3" class="tableFooter">
<br />
<a id="freqQuestionsUserUpdateButton" href="#" class="regularButton">Save</a>
Cancel
</td>
</tr>
</table>
</form>
</asp:Content>
before the page is submitted you need to html encode the textbox's value, with window.escape(...)
If you need the un-escaped text on the server side then use HttpUtility.UrlDecode(...) method.
very quick sample:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SO.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function makeSafe() {
document.getElementById('TextBox1').value = window.escape(document.getElementById('TextBox1').value);
};
function makeDangerous() {
document.getElementById('TextBox1').value = window.unescape(document.getElementById('TextBox1').value);
}
</script>
</head>
<body>
<form id="form1" runat="server" onsubmit="makeSafe();">
<div>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Rows="10" ClientIDMode="Static"></asp:TextBox>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
<script>
makeDangerous();
</script>
</body>
</html>
Make these changes to your code:
<script type="text/javascript">
$(document).ready(function () {
makeDangerous();
$("#freqQuestionsUserUpdateButton").click(function () {
makeSafe();
$("#updateFreqQuestionsUser").submit();
});
});
// Adding an ID attribute to the inputs you want to validate is simplest
// Better would be to use document.getElementsByTagName and filter the array on NAME
// or use a JQUERY select....
function makeSafe() {
document.getElementById('QuestionAnswer').value = window.escape(document.getElementById('QuestionAnswer').value);
};
// In this case adding the HTML back to a textbox should be 'safe'
// You should be very wary though when you use it as actual HTML
// You MUST take steps to ensure the HTML is safe.
function makeDangerous() {
document.getElementById('QuestionAnswer').value = window.unescape(document.getElementById('QuestionAnswer').value);
}
</script>
Decorate your controller action with the [ValidateInput] attribute:
[ValidateInput(false)]
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
...
}
Client JavaScript:
function codificarTags()
{
document.getElementById('txtDescripcion').value = document.getElementById('txtDescripcion').value.replace(/</g,'<').replace(/>/g,'>');
}
<form id="form1" runat="server" onsubmit="codificarTags();">
Server:
protected void Page_Load(object sender, EventArgs e)
{
txtDescripcion.Text = txtDescripcion.Text.Replace(#"<", #"<").Replace(#">", #">");
}
I would suggest using the AjaxControlToolkit's HTML Editor. I'm implementing that now. If you're textbox is multi-line and big enough to accommodate HTML, why not just bump it up to an HTML editor. Your user will be happier too.
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/HTMLEditor/HTMLEditor.aspx
Using html in textbox is not a good practice, maybe use linebreaks (Environment.NewLine) or \r\n instead of br ?
.NET Reference
Example (in C#) :
textBox1.Multiline = true;
textBox1.Text = "test" + Environment.NewLine + "test2";
I took a bit of a different approach. I wanted to use html textboxes widely across my application. I made a user control which would avoid editing the javascript every time I added a new control. My entire control is very custom but the heart of the html handling is as seen below.
The UserControl markup has some simple javascript to escape and unescape the textbox.
<script type="text/javascript">
function UnescapeControl(clientId) {
$('#' + clientId).val(window.unescape($('#' + clientId).val()));
}
function EscapeAllControls() {
var escapeControList = JSON.parse('<%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(EscapeControlList) %>');
for (var i = 0; i < escapeControList.length; i++)
EscapeControl(escapeControList[i]);
}
function EscapeControl(textClientId) {
document.getElementById(textClientId).value = window.escape(document.getElementById(textClientId).value);
}
</script>
<asp:TextBox ID="Txt_SavableText" CssClass="form-control" Width="100%" runat="server" ></asp:TextBox>
The code behind is responsible for escaping the controls before the post back using RegisterOnSubmitStatement and unescaping them using RegisterStartupScript after the post back.
public partial class SavableTextBox : System.Web.UI.UserControl
{
public List<string> EscapeControlList
{
get
{
if (Session["STB_EscapeControlList"] == null)
Session["STB_EscapeControlList"] = new List<string>();
return (List<string>)Session["STB_EscapeControlList"];
}
set { Session["STB_EscapeControlList"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (EscapeHtmlOnPostback && !EscapeControlList.Contains(GetClientId()))
EscapeControlList.Add(GetClientId());
// When using a script manager, you should use ScriptManager instead of ClientScript.
if (EscapeHtmlOnPostback)
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "UnescapeControl_" + GetClientId(), "UnescapeControl('" + GetClientId() + "');", true);
// Ensure we have our escape script called before all post backs containing escapable controls.
// This is like calling OnClientClick before everything.
if (EscapeControlList != null && EscapeControlList.Count > 0)
this.Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "SaveableTextBoxEscaper", "EscapeAllControls();");
}
public string Text
{
get
{
return Txt_SavableText.Text;
}
set
{
Txt_SavableText.Text = value;
}
}
public string GetClientId()
{
return Txt_SavableText.ClientID;
}
}
Now we can use it anywhere like this while setting EscapeHtmlOnPostback="True".
<%# Register TagPrefix="STB" TagName="SavableTextBox" Src="~/SavableTextBox.ascx" %>
<STB:SavableTextBox ID="Txt_HtmlTextBox" EscapeHtmlOnPostback="True" runat="server" />
Note, when we access Txt_HtmlTextBox.Text during the post back it will already be escaped for us.

Categories

Resources