Replace string eg. "[EMAIL]" with a ASP.net Control - asp.net

i have this form i need to build, but a user can have it laid out in different ways.
the layout of the form is kept in a xml file and will contain things like
<div class="holder">
<div>name</div>
<div>[Name]</div>
<div>Surname</div>
<div>[Surname]</div>
<div>Contact Numer</div>
<div>[ContactNumber]</div>
<div>Email</div>
<div>[Email]</div>
<div>[Submit]</div>
</div>
What i need to do is replace those [name]etc.. tags with asp.net controls and be able to read the content of those controls. i have hit a brick wall on this, can anybody help me please.

To create a new control at runtime, from code-behind:
Text Box
TextBox textBox = new TextBox
{
ID = "dynamicTextBox",
Text = "This is a new textbox"
};
[Container].Controls.Add(textBox);
You can do the sae for any other control.

Related

How to bind JSON data to Asp.net Text Box control

I am trying to bind the JSON data to asp.net Text Box control but its not working for me. Where as while binding to HTML control like "paragraph tag" it's working fine.
My code is as follows:
<script>
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
var obj = JSON.parse(text);
document.getElementById("#<%=TextBox1.ClientID%>").val(obj.street);
</script>
Please can any one help me out.

select2 AJAX control disturbs tab ordering

I am using select2 on dropdownlist of asp.net. The code is as follows:
<script type="text/javascript" src="js/select2.min.js"></script>
<link type="text/css" rel="Stylesheet" href="css/select2.css" />
var v = /* get the select control */
v.select2();
The problem is, once select2() function is called, tab ordering stops working. Therefore, when on the dropdownlist tab key is pressed, focus do not move to the control having next highest tabindex but move seemingly randomly to some other control.
Commenting the line where the function is called solve this problem but I need the filtering. I have tried some of the other techniques of filtering discussed here but they are too complicated. Select2 is very simple and useful because all you have to do is include the JS and CSS files and call the function.
How can I solve this ordering problem? Alternatively, is there another filtering option as easy to use as select2 that would help me?
After a few hours of struggle, I have solved the problem. It turns out that the select2 AJAX control do destroy the tab order if the tab is pressed as soon as it gets focus, that is, when nothing is typed in it. It does not, however, destroy tab ordering if some text is typed.
The internal structure of select2's auto-generated HTML is like following:
<div class="select2-container">
<a class="select2-choice">
<span</span>
<abbr class="select2-search-choice-close" />
<div> <b></b> </div>
</a>
<div class="select2-drop select2-offscreen">
<div class="select2-search">
<input class="select2-input select2-focused" tabIndex=<somevalue> />
</div>
<ul class="select2-results></ul>
</div>
</div>
If some text is typed in the HTML select control, then tab ordering is working correctly, if no text is typed then tab order is destroyed. I have used document.activeElement in firebug to find focused control in both cases. In case of no text the anchor element has focus, and in case of text typed the HTML input element has focus.
As shown above, while select2.js correctly set tabIndex property of HTML input element, it does not of the anchor element.
Solution
Just add the following line at the position specified further below in select2.js:
this.container.find("a.select2-choice").attr("tabIndex", this.opts.element.attr("tabIndex"));
Add the line after:
this.opts.element.data("select2", this).hide().after(this.container);
this.container.data("select2", this);
this.dropdown = this.container.find(".select2-drop");
this.dropdown.css(evaluate(opts.dropdownCss));
this.dropdown.addClass(evaluate(opts.dropdownCssClass));
this.dropdown.data("select2", this);
this.results = results = this.container.find(resultsSelector);
this.search = search = this.container.find("input.select2-input");
and before:
search.attr("tabIndex", this.opts.element.attr("tabIndex"));
this.resultsPage = 0;
this.context = null;
// initialize the container
this.initContainer();
this.initContainerWidth();
installFilteredMouseMove(this.results);
this.dropdown.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
installDebouncedScroll(80, this.results);
this.dropdown.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
So it becomes:
this.results = results = this.container.find(resultsSelector);
this.search = search = this.container.find("input.select2-input");
this.container.find("a.select2-choice").attr("tabIndex", this.opts.element.attr("tabIndex")); /* atif */
search.attr("tabIndex", this.opts.element.attr("tabIndex"));
this.resultsPage = 0;
this.context = null;
Make this change in select2.js. Obviously, you need to use the full js version, not the min version.
All you have to do is add one line, stated above. This would become line no#504 in VS2008 if done correctly.

embedding images in asp.net Custom Control

I am creating a custom Gridview control, according to requirement i have to place two image buttons in the Top Pager. where i am able to display imagebuttons in top pager but only one image imagebutton shows the image another imagebutton does not.
Here is code:
protected override void InitializePager(GridViewRow row,int columnSpan,PagedDataSource pagedDataSource)
{
//adding refresh button in TopPager
ImageButton Refresh = new ImageButton();
Refresh.ToolTip = "Refresh GridView";
Refresh.ImageAlign = ImageAlign.Right;
Refresh.AlternateText = "Refresh GridView";
ClientScriptManager cs1 = this.Page.ClientScript;
Refresh.ImageUrl = cs1.GetWebResourceUrl(typeof(myCustomGrid.CustomGrid), "myCustomGrid.Refresh.gif");
// adding button in TopPager to add new record..
ImageButton ExportToPDF = new ImageButton();
ExportToPDF.ToolTip = "Export To PDF";
ExportToPDF.AlternateText = "PDF Export";
ClientScriptManager cs2 = this.Page.ClientScript;
ExportToPDF.ImageUrl = cs2.GetWebResourceUrl(typeof(myCustomGrid.CustomGrid), "myCustomGrid.PDF.gif");
}
I have set both images properties build action to embedded resource
in assembly.info
[assembly: WebResource("myCustomGrid.Refresh.gif", "image/gif")]
[assembly: WebResource("myCustomGird.PDF.gif", "image/gif")]
where i am going wrong! any help is much appreciated.
Does this images placed in root of the project? Because, if not you have to add relative path. And I don't see path from asssembly.
You have to make like this:
[assembly: WebResource("{Your assembly full name}.{Path to image inside assembly and with replacement '/' to '.'}.{Image name}", "image/gif")]
For example:
[assembly: WebResource("MyBestProject.Controls.resources.images.myCustomGird.PDF.gif", "image/gif")]
Could be a typo.
Did you mean :-
[assembly: WebResource("myCustomGrid.PDF.gif", "image/gif")]
and not...
[assembly: WebResource("myCustomGird.PDF.gif", "image/gif")]
Update:
when the imagebuttons renders the HTML generated by Refresh.gif and PDF.gif imagebuttons respectively.The PDF.gif does not load instead i get the alternate text specified which is in this code line ExportToPDF.AlternateText = "PDF Export";
<input align="right" type="image" style="height:20px;width:20px;" alt="Refresh GridView" src="/WebResource.axd?d=CIOcfTt92OMP_aqepr-cGa2E4E8-uaiywsae5-4NcYocrJ-NE-cIL4Qb2JfX3tY0cIa8EwDzWnyeBqNiST34SNpBNuGjVC113XqMTprBN-XU9J7ilPsI6bsaXwHa-Qt30&t=634589418951556073" title="Refresh GridView" name="ctl00$MainContent$customGrid0$ctl01$ctl02">
<input type="image" style="height:20px;width:20px;margin-left:480px;" alt="PDF Export" src="/WebResource.axd?d=su3rsVMzKa7BNi4A-JZVUHPhHh3sS-oWW9bmAeK4I0h1A11NHqBD2setFyA3yundDC34YO0gbBoz5G0PHS0uxeQYI66QON_syQhIdlIKs4JzJW6H_oLErMjOZE6Q_slB0&t=634589418951556073" title="Export To PDF" name="ctl00$MainContent$customGrid0$ctl01$ctl01">
"only" 2 years later, I had a similar issue. I just resolved mine with a simple idea that came by looking at the similarities between this post and my issue. Perhaps someone else will find this solution useful in the future.
The problem appears to be with the ALLCAPS section of the name. For some reason, UpperLower names work fine, as do all lower. But I am guessing ALLCAPS segments get converted to something else internally and don't work. In my case, renaming my icon from "ARROWLEFT.GIF" to "ArrowLeft.gif" (file name, registration, and any references to the resource) fixed the issue.
Additional Note: I had another image in the same project, named "icon_Calendar.GIF" which also wasn't working until I renamed it to "icon_Calendar.gif".

using JavaScript, find the ClientID of .NET control nested deep within a master page

The short question:
*takes deep breath*
How I can ClientID of TableRow inside Table added to PlaceHolder, which is in a UserControl inside a Web Part added to a SharePoint page using a MasterPage?
The explanation:
I'm building a usercontrol that dynamically shows SPList items, one per Web.UI.Table(). The 2nd row of the Table() will be hidden at first, with an image used to initiate some JavaScript to hide/show the row at the clients browser (rather than use postback or ajax - I have reasons).
The Table() is then added to a PlaceHolder in a UserControl, which is then used by a WebPart, and that WebPart is added to a SharePoint Page, which of course uses a MasterPage. I'm having real trouble working out the JavaScript method to find the ClientID of the TableRow, given that it's nested so deeply.
My .ascx code looks something like this..
<script type="text/javascript">
function showHidden(itemId) {
var controlId = document.getElementById('<%= phDownloadTable.ClientID %>');
//alert(controlId);
document.getElementById(controlId).style.display = (document.getElementById(controlId).style.display == "table-row") ? "none" : "table-row";
}
</script>
<asp:PlaceHolder ID="phTable" runat="server"></asp:PlaceHolder>
and my .cs codebehind is something like this..
Table myTable = new Table();
TableRow hiddenRow = new TableRow();
hiddenRow.ID = "row" + itemId;
hiddenRow.Attributes.Add("style","display: none;");
... create TableCells and add to hiddenRow...
TableRow displayRow = new TableRow();
TableCell toggleCell = new TableCell();
Image toggleImage = new Image();
toggleImage.ImageUrl = "/images/myimage";
toggleImage.Attributes.Add("onclick","javascript:showHidden('" + hiddenRow.ClientID + "');
toggleCell.Controls.Add(toggleImage);
displayRow.Cells.Add(toggleCell);
... create more TableCells and add to displayRow
myTable.Rows.Add(displayRow);
myTable.Rows.Add(hiddenRow);
the result is that the toggleImage "onclick" attribute shows showHidden('row999');, which passes 'row999' to the JavaScript function, but I cannot figure out there how to get the full clientId of the TableRow it refers to.
The source of my page shows the clientId to be ctl00_SPWebPartManager1_g_eda9b9e9_4c7a_48e0_a2aa_fd8cdd65de6c_ctl00_row999, which is longer than I'm used to seeing, and seems to contain two 'ct100_' parts, suggesting multiple levels of controls.
Any ideas would be greatly appreciated. I've tried all the usual avenues (googleing for 'javascript .net control client id' and the like, but so far I've not found anything that helps. Most suggest document.getElementById('<%= myControl.ClientId %>')... which is fine, but I don't know 'myControl' - I need that send from the toggle image.
Fingers crossed!!
Kevin
If you cant set the client id, you should be able to set a class, and that should be respected by .nat.
Them you can select the element by class name.
JavaScript has no wildcard selection options. Try using jQuery, that makes things more flexible.
Then you can use something like:
$("tr[id*='<%= phDownloadTable.ClientID %>']").css("display", your value);
this way you will still find the right element, even when it's moved to another place on the page.
Here is a more detailed explanation on how to use these wildcard selectors:
http://api.jquery.com/attribute-contains-selector/
With plain JavaScript you can do a document.getElementsByTagName('tr') and then loop those to find the right object.
If you are using Framework 4.0 you can set the ClientIdMode of the page like this:
Page.ClientIDMode = System.Web.UI.ClientIDMode.Static;
That way you can have more predictable client ids. For example, you can have id's without all the ctl00_ prefixes.

Javascript Rich Display WYSIWYG Component/Methodology

quick back story--
I am working on ASP.Net based template editor that lets authors create text templates using Javascript inserted placeholder tags that will be filled in with dynamic text when the templates are used to display the final results.
For example the author might create a template like
The word [%12#add] was generated dynamically.
The application would eventually replace the tag with a dynamic word down the road (though it's not specifically relevant to this post)
The word foo was generated dynamically.
Depending on the circumstances, the template may be created in a text input, textarea or a modified version of the Ajax Control Toolkit HTML Editor. There might be 40 or more of these editable elements on the page, so using lots of stripped down or modified HTML editors would probably bog the page down too much.
The problem is that the tags such as [%12#add] are displayed inline with the user text and the result is confusing and aesthetically gross. The goal is parse the contens of the source element and when a tags such as [%12#add] are encountered, display something prettier and less cryptic to the user such as a stylable element or image wherever tags such as [%12#add] occur. The application still needs the template text with the tags on postback.
So the user might see
The word tag placeholder was generated dynamically.
but the original template would still be the value of the text input box
The word [%12#add] was generated dynamically.
It seems HTML editors like the ACT version and FckEditor accomplish this by rendering their output in an IFrame, but rather than kill myself trying to roll a lighter specialized version myself, I thought I'd ask if anyone knows of an existing free component or approach that has already tackled this.
With good reason, I don't think S.O. allows HTML formatting, but the bold "tag placeholder" above would ideally be something like tag placeholder.
I think CKEditor might be your best bet. I recently wrote a plugin for it that kept placeholders in the editable content for chunks of content that the user couldn't edit directly. A question I asked may help, particularly the comments to the accepted answer: Update editor content immediately before save in CKEditor plug-in.
The recommendation to me was to look at how object tags (e.g. as used to embed Flash movies) are handled, and from that I was able to proceed fairly quickly. Be aware though that CKEditor is not well documented for plugin developers, so you may often have to resort to looking at the source code.
Final model solution in case someone in the same situation needs a boost.
aspx page:
<div>
<asp:TextBox runat="server" ID="txtTest" TextMode="MultiLine" CssClass="Over" />
<br />
Add CKEdit
<br />
Add Tag
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</div>
<script type= "text/javascript" >
<!--
function ckTest(el) {
var tinyTool = {
toolbar:
[
['Bold', 'Italic', 'UIColor'], ['Styles', 'Format', 'Font', 'FontSize']
]
};
//Note: config.htmlEncodeOutput = true; to work with ASP.NET, see postback for decoding input
var editor = CKEDITOR.replace(el);//, tinyTool);
editor.addCss('.aux1 { background-color: #FFE0C0; border: solid 1px #17659E; }');
}
function insertTag(id, tag, display) {
var e = CKEDITOR.instances[id];
if (e) {
//Storing in comments does not work. stripped out when using insertHtml. Workaround?
//e.insertHtml("<span class='aux1'>" + display + "<!--" + tag + "--></span>");
//Kludge: fake attribute
e.insertHtml("<span class='aux1' tag='" + tag +"'>" + display + "</span> ");
}
}
-->
</script>
-->
</script>
CodeBehind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Note: CKEditor converts single to double quotes in insertHtml
Regex regHiddenTag = new Regex(#"<span\sclass=""\w+""\stag=""(\[%[0-9]{1,2}_[TR]\])"">\w+</span>");
//Note: config.htmlEncodeOutput = true;
string encoded = txtTest.Text
.Replace("<", "<").Replace(">", ">").Replace("&", "&");
//TODO: Use AntiXss Library that I have to thwart bad HTML
string extractedTag = regHiddenTag.Match(encoded).Groups[1].Value;
//store to DB
string template = regHiddenTag.Replace(
encoded,
extractedTag);
//repopulate
string finalText = template.Replace(extractedTag, "foo");
}

Resources