HTMLEditorExtender removes "class", "id" attributes - asp.net

The HTMLEditorExtender seems to be stripping "class" and "id" attributes of my HTML elements, even with EnableSanitization="false".
Is this the default behavior? Is there a work-around?
I'm using the latest release of AjaxControlToolkit.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server" Width="100%"></asp:TextBox>
<ajaxToolkit:HtmlEditorExtender ID="TextBox1_HtmlEditorExtender" runat="server" EnableSanitization="false"
DisplaySourceTab="true" TargetControlID="TextBox1">
</ajaxToolkit:HtmlEditorExtender>
<asp:Button ID="Button1" runat="server" Text="Button" />

You need to download sources of AjaxControlToolkit library and tweak them slightly for your needs. There are two files those must be modified:
HtmlEditorExtenderBehavior.Pre.js
Let's tweak the _encodeHtml function in this file:
_encodeHtml = function () {
//Encode html tags
var isIE = Sys.Browser.agent == Sys.Browser.InternetExplorer;
// code below to the next comment below can be removed completely if you
// want to preserve 'width' attribute as well
var elements = this._editableDiv.getElementsByTagName('*');
var element;
for (var i = 0; element = elements[i]; i++) {
/*
try {
element.className = '';
element.removeAttribute('class');
} catch (ex) { }
try {
element.id = '';
element.removeAttribute('id');
} catch (ex) { } */
try {
element.removeAttribute('width');
} catch (ex) { }
if (isIE) {
}
}
// end of part of code that may be removed
var html = this._editableDiv.innerHTML;
if (isIE) {
//force attributes to be double quoted
var allTags = /\<[^\>]+\>/g;
html = html.replace(allTags, function (tag) {
var sQA = '';
var nQA = '';
if (tag.toLowerCase().substring(0, 2) != '<a') {
sQA = /\=\'([^\'])*\'/g; //single quoted attributes
nQA = /\=([^\"][^\s\/\>]*)/g; //non double quoted attributes
return tag.replace(sQA, '="$1"').replace(nQA, '="$1"');
}
else {
return tag;
}
});
}
//convert rgb colors to hex
var fixRGB = this._rgbToHex;
var replaceRGB = function () {
html = html.replace(/(\<[^\>]+)(rgb\s?\(\d{1,3}\s?\,\s?\d{1,3}\s?\,\s?\d{1,3}\s?\))([^\>]*\>)/gi, function (text, p1, p2, p3) {
return (p1 || '') + ((p2 && fixRGB(p2)) || '') + (p3 || '');
});
};
//twice in case a tag has more than one rgb color in it;
replaceRGB();
replaceRGB();
// remove empty class and id attributes
html = html.replace(/\sclass\=\"\"/gi, '').replace(/\sid\=\"\"/gi, '');
//converter to convert different tags into Html5 standard tags
html = html.replace(/\<(\/?)strong\>/gi, '<$1b>').replace(/\<(\/?)em\>/gi, '<$1i>');
//encode for safe transport
html = html.replace(/&/ig, '&').replace(/\xA0/ig, ' ');
html = html.replace(/</ig, '<').replace(/>/ig, '>').replace(/\'/ig, '&apos;').replace(/\"/ig, '"');
return html;
}
Draw attention to commented block of code above.
HtmlEditorExtender.cs
This is a server control code file and you need to slightly change the Decode method:
public string Decode(string value)
{
EnsureButtons();
string tags = "font|div|span|br|strong|em|strike|sub|sup|center|blockquote|hr|ol|ul|li|br|s|p|b|i|u|img";
string attributes = "style|size|color|face|align|dir|src";
string attributeCharacters = "\\'\\,\\w\\-#\\s\\:\\;\\?\\&\\.\\-\\=";
Add id and class attributes to attributes variable:
string attributes = "style|size|color|face|align|dir|src|class|id";
That's all - build project and use custom dll of ACT library in your project.

Related

Using multi filter datatables in asp.net MVC

I'm trying to implement the multiple filters in the datatables in asp.net, but the time I search a value, my table is not updated.
I followed the official example of the site, but it did not work. Here is the source code I'm using.
JS on VIEW
$('#students tfoot th').each( function () {
var title = $(this).text();
if (title !== "") {
$(this).html('<input type="text" class="form-control form-control-sm" style="width: 100%" placeholder="' + title + '" />');
} else {
$(this).html('<div class="text-center">-</div>');
}
} );
tabela.columns().every( function () {
var that = this;
$( 'input', this.header() ).on( 'keydown', function (ev) {
if (ev.keyCode == 13) { //only on enter keypress (code 13)
that
.search( this.value )
.draw();
}
} );
} );
ACTION on CONTROLLER
[HttpPost]
public JsonResult Listar2()
{
var search = Request.Form.GetValues("search[value]")?[0];
var list = db.Students;
if (!string.IsNullOrEmpty(search))
{
list = list.Where(m => m.name.ToLower().Contains(search.ToLower()) || m.class.ToLower().Contains(search.ToLower()));
}
var draw = Request.Form.GetValues("draw")?[0];
var start = Request.Form.GetValues("start")?[0];
var length = Request.Form.GetValues("length")?[0];
var width = length != null ? Convert.ToInt32(length) : 0;
var skip = start != null ? Convert.ToInt32(start) : 0;
var totalRecords = list.Count();
var resultFinal = list.Skip(skip).Take(width).ToList();
return Json(new
{
data = resultFinal,
draw,
recordsFiltered = totalRecords,
recordsTotal = totalRecords
});
}
I don't know what you want to accomplish. The official example uses JavaScript to sort the datatable which is inserted into HTML already. You should load all the entries first, pass them to the view and then this script should filter those entries

Validation with ajax AutoCompleteExtender

I have a TextBox with AutoCompleteExtenderwhen the person starts typing in the TextBox List with City name Appear .This works fine but now I want to validate that if they just type in a textbox and don't select one from the list that it validates that City Is Not Exist In database.
I want to validate it Using Ajax And Without PostBack Before Final Submit of form.
Add new js file with content below and add add reference on it to ToolkitScriptManager's Scrips collection:
Type.registerNamespace('Sjax');
Sjax.XMLHttpSyncExecutor = function () {
Sjax.XMLHttpSyncExecutor.initializeBase(this);
this._started = false;
this._responseAvailable = false;
this._onReceiveHandler = null;
this._xmlHttpRequest = null;
this.get_aborted = function () {
//Parameter validation code removed here...
return false;
}
this.get_responseAvailable = function () {
//Parameter validation code removed here...
return this._responseAvailable;
}
this.get_responseData = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.responseText;
}
this.get_started = function () {
//Parameter validation code removed here...
return this._started;
}
this.get_statusCode = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.status;
}
this.get_statusText = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.statusText;
}
this.get_xml = function () {
//Code removed
}
this.executeRequest = function () {
//Parameter validation code removed here...
var webRequest = this.get_webRequest();
if (webRequest === null) {
throw Error.invalidOperation(Sys.Res.nullWebRequest);
}
var body = webRequest.get_body();
var headers = webRequest.get_headers();
var verb = webRequest.get_httpVerb();
var xmlHttpRequest = new XMLHttpRequest();
this._onReceiveHandler = Function.createCallback(this._onReadyStateChange, { sender: this });
this._started = true;
xmlHttpRequest.onreadystatechange = this._onReceiveHandler;
xmlHttpRequest.open(verb, webRequest.getResolvedUrl(), false); // False to call Synchronously
if (headers) {
for (var header in headers) {
var val = headers[header];
if (typeof (val) !== "function") {
xmlHttpRequest.setRequestHeader(header, val);
}
}
}
if (verb.toLowerCase() === "post") {
if ((headers === null) || !headers['Content-Type']) {
xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
if (!body) {
body = '';
}
}
this._started = true;
this._xmlHttpRequest = xmlHttpRequest;
xmlHttpRequest.send(body);
}
this.getAllResponseHeaders = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.getAllResponseHeaders();
}
this.getResponseHeader = function (header) {
//Parameter validation code removed here...
return this._xmlHttpRequest.getResponseHeader(header);
}
this._onReadyStateChange = function (e, args) {
var executor = args.sender;
if (executor._xmlHttpRequest && executor._xmlHttpRequest.readyState === 4) {
//Validation code removed here...
executor._responseAvailable = true;
executor._xmlHttpRequest.onreadystatechange = Function.emptyMethod;
executor._onReceiveHandler = null;
executor._started = false;
var webRequest = executor.get_webRequest();
webRequest.completed(Sys.EventArgs.Empty);
//Once the completed callback handler has processed the data it needs from the XML HTTP request we can clean up
executor._xmlHttpRequest = null;
}
}
}
Sjax.XMLHttpSyncExecutor.registerClass('Sjax.XMLHttpSyncExecutor', Sys.Net.WebRequestExecutor);
On a page:
<ajaxToolkit:ToolkitScriptManager runat="server" ID="ScriptManager1">
<Scripts>
<asp:ScriptReference Path="~/XMLHttpSyncExecutor.js" />
</Scripts>
</ajaxToolkit:ToolkitScriptManager>
Then, add CustomValidator for target TextBox and use function below for client validation:
<asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
<asp:CustomValidator runat="server" ID="myTbCustomValidator" ControlToValidate="myTextBox"
Text="*" Display="Dynamic" ValidateEmptyText="false" ClientValidationFunction="validateTextBox"
OnServerValidate="ValidateTextBox" />
function validateTextBox(sender, args) {
if (args.Value.length > 0) {
var extender = $find("AutoCompleteEx"); // AutoComplete extender's BehaviorID
if (extender._completionListElement) {
var children = extender._completionListElement.childNodes;
var length = extender._completionListElement.childNodes.length;
for (var i = 0; i < length; i++) {
if (children[i].innerHTML == args.Value) {
args.IsValid = true;
return;
}
}
}
var request = new Sys.Net.WebRequest();
request.set_url('<%= ResolveClientUrl("~/AutoComplete/AutoComplete.asmx/Validate") %>');
var body = Sys.Serialization.JavaScriptSerializer.serialize({ value: args.Value });
request.set_body(body);
request.set_httpVerb("POST");
request.get_headers()["Content-Type"] = "application/json; encoding=utf-8";
request.add_completed(function (eventArgs) {
var result = Sys.Serialization.JavaScriptSerializer.deserialize(eventArgs.get_responseData());
args.IsValid = result.d;
});
var executor = new Sjax.XMLHttpSyncExecutor();
request.set_executor(executor);
request.invoke();
}
}
The main idea of code above is to check suggested items at first for entered text and if there aren't any concidence then to do synchronous AJAX call to Validate method of web service or page method. That method should have such signature: public bool Validate(string value)
P.S. Code for XMLHttpSyncExecutor taken here: Using Synchronous ASP.Net AJAX Web Service Calls and Scriptaculous to Test your JavaScript

Change textbox's css class when ASP.NET Validation fails

How can I execute some javascript when a Required Field Validator attached to a textbox fails client-side validation? What I am trying to do is change the css class of the textbox, to make the textbox's border show red.
I am using webforms and I do have the jquery library available to me.
Here is quick and dirty thing (but it works!)
<form id="form1" runat="server">
<asp:TextBox ID="txtOne" runat="server" />
<asp:RequiredFieldValidator ID="rfv" runat="server"
ControlToValidate="txtOne" Text="SomeText 1" />
<asp:TextBox ID="txtTwo" runat="server" />
<asp:RequiredFieldValidator ID="rfv2" runat="server"
ControlToValidate="txtTwo" Text="SomeText 2" />
<asp:Button ID="btnOne" runat="server" OnClientClick="return BtnClick();"
Text="Click" CausesValidation="true" />
</form>
<script type="text/javascript">
function BtnClick() {
//var v1 = "#<%= rfv.ClientID %>";
//var v2 = "#<%= rfv2.ClientID %>";
var val = Page_ClientValidate();
if (!val) {
var i = 0;
for (; i < Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid) {
$("#" + Page_Validators[i].controltovalidate)
.css("background-color", "red");
}
}
}
return val;
}
</script>
You could use the following script:
<script>
$(function(){
if (typeof ValidatorUpdateDisplay != 'undefined') {
var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay = function (val) {
if (!val.isvalid) {
$("#" + val.controltovalidate).css("border", "2px solid red");
}
originalValidatorUpdateDisplay(val);
}
}
});
</script>
This code decorates the original ValidatorUpdateDisplay function responsible for updating the display of your validators, updating the controltovalidate as necessary.
Hope this helps,
I think you would want to use a Custom Validator and then use the ClientValidationFunction... Unless it helpfully adds a css class upon fail.
Some time ago I spend a few hours on it and since then I have been using some custom js magic to accomplish this.
In fact is quite simple and in the way that ASP.NET validation works. The basic idea is add a css class to attach a javascript event on each control you want quick visual feedback.
<script type="text/javascript" language="javascript">
/* Color ASP NET validation */
function validateColor(obj) {
var valid = obj.Validators;
var isValid = true;
for (i in valid)
if (!valid[i].isvalid)
isValid = false;
if (!isValid)
$(obj).addClass('novalid', 1000);
else
$(obj).removeClass('novalid', 1000);
}
$(document).ready(function() {
$(".validateColor").change(function() {validateColor(this);});
});
</script>
For instance, that will be the code to add on an ASP.Net textbox control. Yes, you can put as many as you want and it will only imply add a CssClass value.
<asp:TextBox ID="txtBxEmail" runat="server" CssClass="validateColor" />
What it does is trigger ASP.Net client side validation when there is a change on working control and apply a css class if it's not valid. So to customize visualization you can rely on css.
.novalid {
border: 2px solid #D00000;
}
It's not perfect but almost :) and at least your code won't suffer from extra stuff. And
the best, works with all kind of Asp.Net validators, event custom ones.
I haven't seen something like this googling so I wan't to share my trick with you. Hope it helps.
extra stuff on server side:
After some time using this I also add this ".novalid" css class from code behind when need some particular validation on things that perhaps could be only checked on server side this way:
Page.Validate();
if (!requiredFecha.IsValid || !CustomValidateFecha.IsValid)
txtFecha.CssClass = "validateColor novalid";
else
txtFecha.CssClass = "validateColor";
Here is my solution.
Advantages over other solutions:
Integrates seamlessly with ASP.NET - NO changes required to code. Just call the method on page load in a master page.
Automatically changes the CSS class when the text box or control changes
Disadvantages:
Uses some internal features of ASP.NET JavaScript code
Tested only on ASP.NET 4.0
HOW TO USE:
Requires JQuery
Call the "Validation_Load" function when the page loads
Declare a "control_validation_error" CSS class
function Validation_Load() {
if (typeof (Page_Validators) != "object") {
return;
}
for (var i = 0; i < Page_Validators.length; i++) {
var val = Page_Validators[i];
var control = $("#" + val.controltovalidate);
if (control.length > 0) {
var tagName = control[0].tagName;
if (tagName != "INPUT" && tagName != "TEXTAREA" && tagName != "SELECT") {
// Validate sub controls
}
else {
// Validate the control
control.change(function () {
var validators = this.Validators;
if (typeof (validators) == "object") {
var isvalid = true;
for (var k = 0; k < validators.length; k++) {
var val = validators[k];
if (val.isvalid != true) {
isvalid = false;
break;
}
}
if (isvalid == true) {
// Clear the error
$(this).removeClass("control_validation_error");
}
else {
// Show the error
$(this).addClass("control_validation_error");
}
}
});
}
}
}
}
Alternatively, just iterate through the page controls as follows: (needs a using System.Collections.Generic reference)
const string CSSCLASS = " error";
protected static Control FindControlIterative(Control root, string id)
{
Control ctl = root;
LinkedList<Control> ctls = new LinkedList<Control>();
while ( ctl != null )
{
if ( ctl.ID == id ) return ctl;
foreach ( Control child in ctl.Controls )
{
if ( child.ID == id ) return child;
if ( child.HasControls() ) ctls.AddLast(child);
}
ctl = ctls.First.Value;
ctls.Remove(ctl);
}
return null;
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Add css classes to invalid items
if ( Page.IsPostBack && !Page.IsValid )
{
foreach ( BaseValidator item in Page.Validators )
{
var ctrltoVal = (WebControl)FindControlIterative(Page.Form, item.ControlToValidate);
if ( !item.IsValid ) ctrltoVal.CssClass += " N";
else ctrltoVal.CssClass.Replace(" N", "");
}
}
}
Should work for most cases, and means you dont have to update it when you add validators. Ive added this code into a cstom Pageclass so it runs site wide on any page I have added validators to.

Is there a workaround for IE 6/7 "Unspecified Error" bug when accessing offsetParent

I'm using jQuery UI's draggable and droppable libraries in a simple ASP.NET proof of concept application. This page uses the ASP.NET AJAX UpdatePanel to do partial page updates. The page allows a user to drop an item into a trashcan div, which will invoke a postback that deletes a record from the database, then rebinds the list (and other controls) that the item was drug from. All of these elements (the draggable items and the trashcan div) are inside an ASP.NET UpdatePanel.
Here is the dragging and dropping initialization script:
function initDragging()
{
$(".person").draggable({helper:'clone'});
$("#trashcan").droppable({
accept: '.person',
tolerance: 'pointer',
hoverClass: 'trashcan-hover',
activeClass: 'trashcan-active',
drop: onTrashCanned
});
}
$(document).ready(function(){
initDragging();
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function()
{
initDragging();
});
});
function onTrashCanned(e,ui)
{
var id = $('input[id$=hidID]', ui.draggable).val();
if (id != undefined)
{
$('#hidTrashcanID').val(id);
__doPostBack('btnTrashcan','');
}
}
When the page posts back, partially updating the UpdatePanel's content, I rebind the draggables and droppables. When I then grab a draggable with my cursor, I get an "htmlfile: Unspecified error." exception. I can resolve this problem in the jQuery library by replacing elem.offsetParent with calls to this function that I wrote:
function IESafeOffsetParent(elem)
{
try
{
return elem.offsetParent;
}
catch(e)
{
return document.body;
}
}
I also have to avoid calls to elem.getBoundingClientRect() as it throws the same error. For those interested, I only had to make these changes in the jQuery.fn.offset function in the Dimensions Plugin.
My questions are:
Although this works, are there better ways (cleaner; better performance; without having to modify the jQuery library) to solve this problem?
If not, what's the best way to manage keeping my changes in sync when I update the jQuery libraries in the future? For, example can I extend the library somewhere other than just inline in the files that I download from the jQuery website.
Update:
#some It's not publicly accessible, but I will see if SO will let me post the relevant code into this answer. Just create an ASP.NET Web Application (name it DragAndDrop) and create these files. Don't forget to set Complex.aspx as your start page. You'll also need to download the jQuery UI drag and drop plug in as well as jQuery core
Complex.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Complex.aspx.cs" Inherits="DragAndDrop.Complex" %>
<!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>
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery-ui-personalized-1.5.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
function initDragging()
{
$(".person").draggable({helper:'clone'});
$("#trashcan").droppable({
accept: '.person',
tolerance: 'pointer',
hoverClass: 'trashcan-hover',
activeClass: 'trashcan-active',
drop: onTrashCanned
});
}
$(document).ready(function(){
initDragging();
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function()
{
initDragging();
});
});
function onTrashCanned(e,ui)
{
var id = $('input[id$=hidID]', ui.draggable).val();
if (id != undefined)
{
$('#hidTrashcanID').val(id);
__doPostBack('btnTrashcan','');
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="updContent" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:LinkButton ID="btnTrashcan" Text="trashcan" runat="server" CommandName="trashcan"
onclick="btnTrashcan_Click" style="display:none;"></asp:LinkButton>
<input type="hidden" id="hidTrashcanID" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
<table>
<tr>
<td style="width: 300px;">
<asp:DataList ID="lstAllPeople" runat="server" DataSourceID="odsAllPeople"
DataKeyField="ID">
<ItemTemplate>
<div class="person">
<asp:HiddenField ID="hidID" runat="server" Value='<%# Eval("ID") %>' />
Name:
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
<br />
<br />
</div>
</ItemTemplate>
</asp:DataList>
<asp:ObjectDataSource ID="odsAllPeople" runat="server" SelectMethod="SelectAllPeople"
TypeName="DragAndDrop.Complex+DataAccess"
onselecting="odsAllPeople_Selecting">
<SelectParameters>
<asp:Parameter Name="filter" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
</td>
<td style="width: 300px;vertical-align:top;">
<div id="trashcan">
drop here to delete
</div>
<asp:DataList ID="lstPeopleToDelete" runat="server"
DataSourceID="odsPeopleToDelete">
<ItemTemplate>
ID:
<asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' />
<br />
Name:
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:ObjectDataSource ID="odsPeopleToDelete" runat="server"
onselecting="odsPeopleToDelete_Selecting" SelectMethod="GetDeleteList"
TypeName="DragAndDrop.Complex+DataAccess">
<SelectParameters>
<asp:Parameter Name="list" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Complex.aspx.cs
namespace DragAndDrop
{
public partial class Complex : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected List<int> DeleteList
{
get
{
if (ViewState["dl"] == null)
{
List<int> dl = new List<int>();
ViewState["dl"] = dl;
return dl;
}
else
{
return (List<int>)ViewState["dl"];
}
}
}
public class DataAccess
{
public IEnumerable<Person> SelectAllPeople(IEnumerable<int> filter)
{
return Database.SelectAll().Where(p => !filter.Contains(p.ID));
}
public IEnumerable<Person> GetDeleteList(IEnumerable<int> list)
{
return Database.SelectAll().Where(p => list.Contains(p.ID));
}
}
protected void odsAllPeople_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["filter"] = this.DeleteList;
}
protected void odsPeopleToDelete_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["list"] = this.DeleteList;
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (int id in DeleteList)
{
Database.DeletePerson(id);
}
DeleteList.Clear();
lstAllPeople.DataBind();
lstPeopleToDelete.DataBind();
}
protected void btnTrashcan_Click(object sender, EventArgs e)
{
int id = int.Parse(hidTrashcanID.Value);
DeleteList.Add(id);
lstAllPeople.DataBind();
lstPeopleToDelete.DataBind();
}
}
}
Database.cs
namespace DragAndDrop
{
public static class Database
{
private static Dictionary<int, Person> _people = new Dictionary<int,Person>();
static Database()
{
Person[] people = new Person[]
{
new Person("Chad")
, new Person("Carrie")
, new Person("Richard")
, new Person("Ron")
};
foreach (Person p in people)
{
_people.Add(p.ID, p);
}
}
public static IEnumerable<Person> SelectAll()
{
return _people.Values;
}
public static void DeletePerson(int id)
{
if (_people.ContainsKey(id))
{
_people.Remove(id);
}
}
public static Person CreatePerson(string name)
{
Person p = new Person(name);
_people.Add(p.ID, p);
return p;
}
}
public class Person
{
private static int _curID = 1;
public int ID { get; set; }
public string Name { get; set; }
public Person()
{
ID = _curID++;
}
public Person(string name)
: this()
{
Name = name;
}
}
}
#arilanto - I include this script after my jquery scripts. Performance wise, it's not the best solution, but it is a quick easy work around.
function IESafeOffsetParent(elem)
{
try
{
return elem.offsetParent;
}
catch(e)
{
return document.body;
}
}
// The Offset Method
// Originally By Brandon Aaron, part of the Dimension Plugin
// http://jquery.com/plugins/project/dimensions
jQuery.fn.offset = function() {
/// <summary>
/// Gets the current offset of the first matched element relative to the viewport.
/// </summary>
/// <returns type="Object">An object with two Integer properties, 'top' and 'left'.</returns>
var left = 0, top = 0, elem = this[0], results;
if ( elem ) with ( jQuery.browser ) {
var parent = elem.parentNode,
offsetChild = elem,
offsetParent = IESafeOffsetParent(elem),
doc = elem.ownerDocument,
safari2 = safari && parseInt(version) < 522 && !/adobeair/i.test(userAgent),
css = jQuery.curCSS,
fixed = css(elem, "position") == "fixed";
// Use getBoundingClientRect if available
if (false && elem.getBoundingClientRect) {
var box = elem.getBoundingClientRect();
// Add the document scroll offsets
add(box.left + Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
box.top + Math.max(doc.documentElement.scrollTop, doc.body.scrollTop));
// IE adds the HTML element's border, by default it is medium which is 2px
// IE 6 and 7 quirks mode the border width is overwritable by the following css html { border: 0; }
// IE 7 standards mode, the border is always 2px
// This border/offset is typically represented by the clientLeft and clientTop properties
// However, in IE6 and 7 quirks mode the clientLeft and clientTop properties are not updated when overwriting it via CSS
// Therefore this method will be off by 2px in IE while in quirksmode
add( -doc.documentElement.clientLeft, -doc.documentElement.clientTop );
// Otherwise loop through the offsetParents and parentNodes
} else {
// Initial element offsets
add( elem.offsetLeft, elem.offsetTop );
// Get parent offsets
while ( offsetParent ) {
// Add offsetParent offsets
add( offsetParent.offsetLeft, offsetParent.offsetTop );
// Mozilla and Safari > 2 does not include the border on offset parents
// However Mozilla adds the border for table or table cells
if ( mozilla && !/^t(able|d|h)$/i.test(offsetParent.tagName) || safari && !safari2 )
border( offsetParent );
// Add the document scroll offsets if position is fixed on any offsetParent
if ( !fixed && css(offsetParent, "position") == "fixed" )
fixed = true;
// Set offsetChild to previous offsetParent unless it is the body element
offsetChild = /^body$/i.test(offsetParent.tagName) ? offsetChild : offsetParent;
// Get next offsetParent
offsetParent = offsetParent.offsetParent;
}
// Get parent scroll offsets
while ( parent && parent.tagName && !/^body|html$/i.test(parent.tagName) ) {
// Remove parent scroll UNLESS that parent is inline or a table to work around Opera inline/table scrollLeft/Top bug
if ( !/^inline|table.*$/i.test(css(parent, "display")) )
// Subtract parent scroll offsets
add( -parent.scrollLeft, -parent.scrollTop );
// Mozilla does not add the border for a parent that has overflow != visible
if ( mozilla && css(parent, "overflow") != "visible" )
border( parent );
// Get next parent
parent = parent.parentNode;
}
// Safari <= 2 doubles body offsets with a fixed position element/offsetParent or absolutely positioned offsetChild
// Mozilla doubles body offsets with a non-absolutely positioned offsetChild
if ( (safari2 && (fixed || css(offsetChild, "position") == "absolute")) ||
(mozilla && css(offsetChild, "position") != "absolute") )
add( -doc.body.offsetLeft, -doc.body.offsetTop );
// Add the document scroll offsets if position is fixed
if ( fixed )
add(Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
Math.max(doc.documentElement.scrollTop, doc.body.scrollTop));
}
// Return an object with top and left properties
results = { top: top, left: left };
}
function border(elem) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
add( jQuery.curCSS(elem, "borderLeftWidth", true), jQuery.curCSS(elem, "borderTopWidth", true) );
}
function add(l, t) {
/// <summary>
/// This method is internal.
/// </summary>
/// <private />
left += parseInt(l, 10) || 0;
top += parseInt(t, 10) || 0;
}
return results;
};
If you would like to fix the minified/compressed .js file for jQuery version 1.4.2, replace:
var d=b.getBoundingClientRect(),
with
var d = null;
try { d = b.getBoundingClientRect(); }
catch(e) { d = { top : b.offsetTop, left : b.offsetLeft } ; }
(note that there is no comma after the closing brace now)
i tried the following workaround for the getBoundingClientRect() unspecified error whilst drag n drop, and it works fine.
in the jquery.1.4.2.js (i.e base jquery file, where the error is thrown exactly)
replace the elem.getBoundingClientRect() function call in js file
//the line which throws the unspecified error
var box = elem.getBoundingClientRect(),
with this..
var box = null;
try
{
box = elem.getBoundingClientRect();
}
catch(e)
{
box = { top : elem.offsetTop, left : elem.offsetLeft } ;
}
This solves the issue and drag n drop will work quitely even after post back through update panel
Regards
Raghu
My version is:
Add function:
function getOffsetSum(elem) {
var top = 0, left = 0
while (elem) {
top = top + parseInt(elem.offsetTop)
left = left + parseInt(elem.offsetLeft)
try {
elem = elem.offsetParent
}
catch (e) {
return { top: top, left: left }
}
}
return { top: top, left: left }
};
replace
var box = this[0].getBoundingClientRect()
with
var box = getOffsetSum(this[0])
PS: jquery-1.3.2.
#Raghu
Thanks for this bit of code! I was having the same problem in IE and this fixed it.
var box = null;
try {
box = elem.getBoundingClientRect();
} catch(e) {
box = {
top : elem.offsetTop,
left : elem.offsetLeft
};
}
This isn't just a jQuery error. I encountered it using ExtJS 4.0.2a on IE8. It seems that IE will almost always stumble on element.getBoundingClientRect() if the element has been replaced in the DOM. Your try/catch hack is pretty much the only way to get around this. I guess the actual solution would be to eventually drop IE < 9 support.
Relevent ExtJS v4.0.2a Source Code (lines 11861-11869):
...
if(el != bd){
hasAbsolute = fly(el).isStyle("position", "absolute");
if (el.getBoundingClientRect) {
b = el.getBoundingClientRect();
scroll = fly(document).getScroll();
ret = [Math.round(b.left + scroll.left), Math.round(b.top + scroll.top)];
} else {
...
With a try/catch fix:
...
if(el != bd){
hasAbsolute = fly(el).isStyle("position", "absolute");
if (el.getBoundingClientRect) {
try {
b = el.getBoundingClientRect();
scroll = fly(document).getScroll();
ret = [Math.round(b.left + scroll.left), Math.round(b.top + scroll.top)];
} catch(e) {
ret = [0,0];
}
} else {
...

Are there caveats to dynamicly creating a form with javascript?

I have to do a cross site POST (with a redirection, so not using a XMLHTTPRequest), and the base platform is ASP.NET. I don't want to POST all of the controls in the ASP.NET FORM to this other site, so I was considering dynamicly creating a new form element using javascript and just posting that.
Has anyone tried this trick? Is there any caveats?
I do this all the time. Works really well. You will have to look through the Request's parameters manually, though, unless you get creative with what you pass as the parameters won't map onto controls on that page. You could also do this in a REST way by passing the parameters in the query string, but I prefer the forms approach to keep my URLs clean. Note that ASP.NET ignores all forms but it's own on postback so I don't bother removing them.
Example from a GridView template field for below code:
<asp:TemplateField HeaderText="Station" SortExpression="Name">
<ItemTemplate>
<a href="javascript:void(0);" onclick='Redirector.redirect_with_id("StationDetail.aspx", <%# Eval("StationID") != null ? Eval("StationID") : "-1" %>);return false;'>
<asp:Label ID="nameLabel" runat="server" Text='<%# Bind("Name") %>' /></a>
</ItemTemplate>
</asp:TemplateField>
Code below -- requires Prototype:
// JScript File
var Redirector = Class.create();
Redirector.prototype = {
initialize: function(url,target) {
this.url = url;
this.parameters = new Hash();
this.target = target;
},
addParameter: function(id,value) {
this.parameters.set(id, value);
},
redirect: function() {
var form = document.createElement('form');
document.body.appendChild(form);
form.action = this.url;
form.method = "post";
if (this.target) {
form.target = this.target;
}
this.parameters.each( function(pair) {
var input = document.createElement('input');
input.id = pair.key;
input.name = pair.key;
input.value = pair.value;
input.style.display = 'none';
form.appendChild(input);
});
form.submit();
}
};
Redirector.redirect_with_id = function(url,id,target) {
var redirector = new Redirector( url, target );
redirector.addParameter( 'ID', id );
redirector.redirect();
};
Redirector.redirect_with_tag = function(url,tag_name,tag,target) {
var redirector = new Redirector( url, target );
redirector.addParameter( tag_name, tag );
redirector.redirect();
};
Redirector.redirect_with_tags = function(url,tag_names_comma_separated,tag_values_comma_separated,target) {
var redirector = new Redirector( url, target );
var tags = tag_names_comma_separated.split( "," );
var values = tag_values_comma_separated.split( ",");
for( var i = 0; i< tags.length; i++ )
{
redirector.addParameter( tags[i], values[i] );
}
redirector.redirect();
};
One caveat: you cannot add a FORM tag to the document using innerHTML. You must add it by creating a new DOM element. You can add fields using innerHTML, but not the form itself.

Resources