I've an aspx page and that page has a table like below
<table id="tbl1" runat="server">
<tr>
<td>
Hello world
</td>
</tr>
</table>
Now I want to get the position of the table (x,y coordinates) from code behind (C#).
Is there any way to get it?
Try this
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function getPosition(elmID) {
var elmPosition = $("#"+elmID).position();
$("#<%= hdnPosition.ClientID%>").val(elmPosition.left + "," + elmPosition.top);
}
$(document).ready(function () {
$("#<%= btnGetPosition.ClientID %>").click(function () {
getPosition("tbl1");
});
});
</script>
</head>
<body>
<form id="frmMain" runat="server">
<table id="tbl1" runat="server">
<tr>
<td>
Hello world
</td>
</tr>
</table>
<asp:HiddenField ID="hdnPosition" runat="server" />
<asp:Button ID="btnGetPosition" runat="server" Text="Get position"
onclick="btnGetPosition_Click"/>
</form>
</body>
</html>
Codebehind:
protected void btnGetPosition_Click(object sender, EventArgs e)
{
string position = hdnPosition.Value;
}
You can achieve this with many ways
add a placeholder and put your table at runtime:-
<asp:placeholder id="PlaceHolder1" runat="server" xmlns:asp="#unknown">
</asp:placeholder>
set CSS at runtime
style1
{
position:absolute;
left:100px; //Example
top:150px; //Example
}
in CS code, use
Table.CssClass = "style1";
You can use Control.Style Property to set style of a control:
Table tbl = new Table();
tbl.Style[HtmlTextWriterStyle.Position] = "Absolute";
tbl.Style[HtmlTextWriterStyle.Top] = "10px";
If you want it in complete JavaScript. For example:
<!DOCTYPE html>
<head>
<title>Overlapping tables</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<style type="text/css" media="all">
table.first
{
position: absolute;
margin: 0;
padding: 0;
color: #000000;
background-color: #ff0000;
text-align: center;
}
table.second
{
margin: 0;
padding: 0;
position: relative;
text-align: center;
color: #00ff00;
background-color: transparent;
}
</style>
<script type="text/javascript"><!--
onload = setPos;
function setPos ()
{
var table_1 = new namedTable ('first_table');
var table_2 = new namedTable ('second_table');
table_2.style.top = table_1.style.top - 1;
table_2.style.left = table_1.style.left - 1;
}
function namedTable(name)
{
if (document.getElementById)
{
this.obj = document.getElementById(name);
this.style = document.getElementById(name).style;
}
else if (document.all)
{
this.obj = document.all[name];
this.style = document.all[name].style;
}
else if (document.layers)
{
this.obj = document.layers[name];
this.style = document.layers[name];
}
}
//--></script>
</head>
<body>
<table class="first" id="first_table">
<tr>
<td>
<h1>TABLE</h1>
</td>
</tr>
</table>
<table class="second" id="second_table">
<tr>
<td>
<h1>TABLE</h1>
</td>
</tr>
</table>
</body>
</html>
Notes:
1) The document still validates (both CSS and HTML) at w3.org.
2) It is tested in Mozilla and Internet Explorer.
3) By force of habit I use the doc-type xhtml1-strict.dtd, but you should
not use this doctype when publishing for Mozilla. Use HTML
transitional instead - or simply put in no header (which will let the
browsers run in Quirk mode, and be more lenient towards scripting
errors).
4)
If you further want to study this topic, here is a link to the most
precise and lightweight Javascript Positioning techniques I know of:
http://www.quirksmode.org/
Good luck!
Related
I'm going through a sample using drag and drop of a grid view where you can re-order the data. I'm trying to find out once the user has re-ordered the grid view how they like it how can I get the data in the first column in the order that they have changed it to. I've tried adding a bit of code to the button event to get this but it only gets the original order and not that of what the user changed it to.
ASPX Page: -
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 id="Head1" runat="server">
<title>Untitled Page</title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
<script type="text/javascript">
$(function () {
$(".drag_drop_grid").sortable({
items: 'tr:not(tr:first-child)',
cursor: 'crosshair',
connectWith: '.drag_drop_grid',
axis: 'y',
dropOnEmpty: true,
receive: function (e, ui) {
$(this).find("tbody").append(ui.item);
}
});
$("[id*=gvDest] tr:not(tr:first-child)").remove();
});
</script>
<style type="text/css">
.GridSrc td
{
background-color: #A1DCF2;
color: black;
font-size: 10pt;
font-family:Arial;
line-height: 200%;
cursor: pointer;
width:100px
}
.GridSrc th
{
background-color: #3AC0F2;
color: White;
font-family:Arial;
font-size: 10pt;
line-height: 200%;
width:100px;
}
.GridDest td
{
background-color: #eee !important;
color: black;
font-family:Arial;
font-size: 10pt;
line-height: 200%;
cursor: pointer;
width:100px
}
.GridDest th
{
background-color: #6C6C6C !important;
color: White;
font-family:Arial;
font-size: 10pt;
line-height: 200%;
width:100px
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvSource" runat="server" CssClass="drag_drop_grid GridSrc" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Item"/>
<asp:BoundField DataField="Price" HeaderText="Price"/>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
</html>
ASPX.CS Page: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Item"), new DataColumn("Price") });
dt.Rows.Add("Shirt", 450);
dt.Rows.Add("Jeans", 3200);
dt.Rows.Add("Trousers", 1900);
dt.Rows.Add("Tie", 185);
dt.Rows.Add("Cap", 100);
dt.Rows.Add("Hat", 120);
dt.Rows.Add("Scarf", 290);
dt.Rows.Add("Belt", 150);
gvSource.UseAccessibleHeader = true;
gvSource.DataSource = dt;
gvSource.DataBind();
dt.Rows.Clear();
dt.Rows.Add();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvSource.Rows)
{
Response.Write(row.Cells[0].Text.ToString());
}
}
}
You can use jquery 'tableDnD' plugin along with asp.net listview OR repeater.
Like this:
ASP.NET
<asp:Repeater>
<ItemTemplate>
<tr id='<%# Eval("ItemID") %>'>
<!-- Assign the unique key as the id of the row. -->
...
</tr>
</ItemTemplate>
</asp:Repeater>
JQuery
$(document).ready(function () {
$("#tbl").tableDnD({
onDrop: function (table, row) {
var RowIDs = '';
$('#tbl tr').each(function () {
RowIDs += $(this).attr('id') + ",";
});
$('#<%= hdnIDs.ClientID %>').val(RowIDs);
// Save the resulting sequence in a hidden field.
$('#<%= btnSaveOrder.ClientID %>').click();
// Postback the page and process the new sequence on server side.
},
onDragClass: "myDragClass",
});
});
I have an asp.net 4.5 app using this as the base. I'm trying to find the bug in my code as it doesn't return the value from my modalpopup back to my 'TextBox1' on my default page.
I have a default.aspx page with the following:
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="btnSelectFolder" runat="server" Text="Select Folder" OnClientClick="showDirectory();"/>
The default.aspx references my Site.Master page with the following JavaScript
<html lang="en">
<head runat="server">
<meta charset="utf-8" />
<title><%: Page.Title %> - My ASP.NET Application</title>
<asp:PlaceHolder runat="server">
<%: Scripts.Render("~/bundles/modernizr") %>
</asp:PlaceHolder>
<webopt:BundleReference runat="server" Path="~/Content/css" />
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
<asp:ContentPlaceHolder runat="server" ID="HeadContent" />
<script type="text/javascript">
function showDirectory() {
document.all.TextBox1.value = window.showModalDialog("browseDirectory.aspx",
'jain',
"dialogHeight: 560px; dialogWidth:360px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No;");
return false;
}
</script>
</head>
On my modalPopup (BrowseDirectory.aspx) I have the following JavaScript (SelectAndClose() function) that should return the contents of the _browseTextBox to my original Default.aspx page , but it returns a null error ( I included the entire header section):
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="BrowseDirectory.aspx.cs" Inherits="DirectoryBrowsin.BrowseDirectory" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Borwse Directory</title>
<style>
.errorMsg{FONT-SIZE: 8.25pt; COLOR: red; FONT-FAMILY: Verdana, Arial; TEXT-DECORATION: none }
.hilite { BACKGROUND-COLOR: #dfe5ff }
.nohilite { BACKGROUND-COLOR: #ffffff }
.text { FONT-SIZE: 8.25pt; COLOR: black; FONT-FAMILY: Verdana, Arial; TEXT-DECORATION: none }
.tableOutlineWt { BORDER-RIGHT: #cccccc 1px solid; BORDER-TOP: #666666 1px solid; MARGIN-TOP: 0px; OVERFLOW: auto; BORDER-LEFT: #333333 1px solid; PADDING-TOP: 0px; BORDER-BOTTOM: #cccccc 1px solid }
</style>
<script type="text/javascript">
function SelectAndClose()
{
txtValue = document.getElementById('_browseTextBox');
window.returnValue = txtValue.value;
window.close();
return false;
}
</script>
</head>
window.shoModalDialog is not implemented the same in all browsers. It first appeared in one of the earlier Internet Explorer browsers. Take a look at this SO answer on this topic: https://stackoverflow.com/a/10234548/2488939
I am using slayeroffice's custom alert box, slayeroffice(period)com/code/custom_alert/. (Can't post more than two links) On my browser it shows up like this. The alert box is the blue one in the middle of the screen.
http://i.stack.imgur.com/u1TEz.png
On my local it shows up like this, I highlighted the alert box. I wish i could image link this.
It works on the same version version of browser but one of them is on local.
http://i.stack.imgur.com/0xehV.png
What am I doing wrong?
Here's my code integrated with slayeroffice's code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test1" %>
<%# Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<!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>Untitled Page</title>
</head>
<body>
<script type="text/javascript">
function showPopUp(){
setTimeout(function() {alert("Warning");}, 5000);
}
function delayer(){
showPopUp();
}
// constants to define the title of the alert and button text.
var ALERT_TITLE = "Oops!";
var ALERT_BUTTON_TEXT = "Ok";
// over-ride the alert method only if this a newer browser.
// Older browser will see standard alerts
if(document.getElementById) {
window.alert = function(txt) {
createCustomAlert(txt); //overrides alert method
}
}
function createCustomAlert(txt) {
// shortcut reference to the document object
d = document;
// if the modalContainer object already exists in the DOM, bail out.
if(d.getElementById("modalContainer")) return;
// create the modalContainer div as a child of the BODY element
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "modalContainer";
// make sure its as tall as it needs to be to overlay all the content on the page
mObj.style.height = document.documentElement.scrollHeight + "px";
// create the DIV that will be the alert
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "alertBox";
// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
if(false) alertObj.style.top = document.documentElement.scrollTop + "px";
// center the alert box
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
// create an H1 element as the title bar
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
// create a paragraph element to contain the txt argument
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = txt;
// create an anchor element to use as the confirmation button.
btn = alertObj.appendChild(d.createElement("a"));
btn.id = "closeBtn";
btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
btn.href = "#";
// set up the onclick event to remove the alert when the anchor is clicked
btn.onclick = function() { removeCustomAlert();return false; }
}
// removes the custom alert from the DOM
function removeCustomAlert() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}
</script>
<form id="form1" runat="server">
<div>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="delayer();return false;" />
</form>
</body>
</html>
You are missing the styles:
<style type="text/css">
#modalContainer {
background-color:transparent;
position:absolute;
width:100%;
height:100%;
top:0px;
left:0px;
z-index:10000;
background-image:url(tp.png); /* required by MSIE to prevent actions on lower z-index elements */
}
#alertBox {
position:relative;
width:300px;
min-height:100px;
margin-top:50px;
border:2px solid #000;
background-color:#F2F5F6;
background-image:url(alert.png);
background-repeat:no-repeat;
background-position:20px 30px;
}
#modalContainer > #alertBox {
position:fixed;
}
#alertBox h1 {
margin:0;
font:bold 0.9em verdana,arial;
background-color:#78919B;
color:#FFF;
border-bottom:1px solid #000;
padding:2px 0 2px 5px;
}
#alertBox p {
font:0.7em verdana,arial;
height:50px;
padding-left:5px;
margin-left:55px;
}
#alertBox #closeBtn {
display:block;
position:relative;
margin:5px auto;
padding:3px;
border:2px solid #000;
width:70px;
font:0.7em verdana,arial;
text-transform:uppercase;
text-align:center;
color:#FFF;
background-color:#78919B;
text-decoration:none;
}
</style>
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.
In my winforms aplication I have a WebBrowser control named webBrowser1.
In code all I added is navigating to a page:
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://localhost:6489/Default.aspx");
}
The code for the page to which I navigate is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TableRowShow.Default" %>
<!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 type="text/javascript">
window.onload = function()
{
document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
}
function attach()
{
document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
}
var i = 1; // position of next tr to be shown
function addDest()
{
var trs = document.getElementById('travelTable').getElementsByTagName('tr');
if (trs[i] != null)
trs[i++].style.display = "";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="travelTable">
<tr>
<td>
<asp:TextBox runat="server" />
</td>
</tr>
<tr style="display: none">
<td>
<asp:TextBox runat="server" />
</td>
</tr>
<tr style="display: none">
<td>
<asp:TextBox runat="server" />
</td>
</tr>
</table>
<asp:HyperLink runat="server" ID="addDestination"
ClientIDMode="Static" NavigateUrl="javascript:;" >
Add Destination
</asp:HyperLink>
</form>
</body>
</html>
Seen in a browser like IE or Chrome the page looks like this:
Clicking on Add Destination anchor creates a new input:
The problem that I'm having with WebBrowser control is that it loads the page but the JavaScript doesn't work.
If I click on Add Destination nothing happens, even though the same page works well in Chrome or IE.
Placing a breakpoint and using:
webBrowser1.Document.InvokeScript("addDestination");
inside the Immediate window and then continuing to run the program activates the JavaScript in that function adding a new input.
Thanks for replies!
Try attaching the click handlers like this instead of using setAttribute in the onload and attach functions:
document.getElementById('addDestination').onclick = addDest;
You could try setting the ScriptErrorsSuppressed property to false to see whether any JavaScript errors occur.