Dynamic load of html code - c#

In my Asp.net website I have a repeater which loads dynamically from code-behind. In code outside the repeater I have an "add" button. On click, I want to add the same controls from repeater asynchronously. On click of the "add" button function NewRow() is called:
function NewRow(){
var guid = jQuery.guid++;
var panel = $('#MainContent_Panel1');
var textboxText = $('#MainContent_TextBox');
panel.after("<span LabelGroup="+i+">Test Text:</span>
<span TextGroup="+i+">"+textboxText.val()+"<br /></span>
<span LabelGroup="+i+">Test Text : </span>
<input type='text' customID="+guid+"/>
<input type='button' Class='Button' ButtonGroup='"+i+"' value='Button Text' /></br>
");
i++;
}
I hate what I am currently doing, because there is so much hardcoded code. Is there any way I can make it more dynamic?
And is there any way to place my newly added row more precisely in dynamic control like repeater?

You could try a templating engine like mustache.js, or you can do it by hand like this:
In your HTML, include a script tag, with type="text/html". This will tell the rendering engine to do not try to render the contents. Inside this tag, you will write the template code for each column.
I marked each variable section as $variable:
$i
$textboxText
$guid
​<script type="text/html"​​​​​​​​​​​​​​​​ id="template">
<span LabelGroup='$i'>Test Text:</span>
<span TextGroup='$i'>$textboxText<br /></span>
<span LabelGroup='$i'>Test Text : </span>
<input type='text' customID='$guid'/>
<input type='button' Class='Button' ButtonGroup='$i' value='Button Text' /></br>
</script>
<!-- And here, some testing elements -->
​<input type="button" id="New" value="New Row">
<input type="text" id="MainContent_TextBox" value="Some Value">
<div id="MainContent_Panel1"></div>​​​​​​​
And then, in your javascript, you only need to get the html contents of the script tag, then replace each $variable with the value to use.
Please note that you should use /g when calling .replace, to replace all ocurrencies of your $variable in the template.
i = 1;
$("#New").click(NewRow);
function NewRow(){
var guid = jQuery.guid++;
var panel = $('#MainContent_Panel1');
var textboxText = $('#MainContent_TextBox').val();
var html = $("#template").html()
.replace(/\$i/g,i)
.replace(/\$guid/g,guid)
.replace(/\$textboxText/g,textboxText);
panel.append(html);
i++;
​}​
Using this approach, you are separating html from js code. Something that will help you in the future if you have to maintain this.
Hope it helps.

You could create your tags on the fly like this:
var $span1 = $("<span />").text("your text").attr("TextGroup", i);
...
var $text = $('<input type="text" />').attr("customID", guid);
...
var $button = $('<input type="button" />').addClass("Button").val("Button text").attr("ButtonGroup", i);
And then just add them to the control container
$panel.append($span1).append(...);
Try it live on Fiddler

Related

Additional html tags with dynamic radio button

I am creating some radio buttons dynamically by:
Regions.ascx
<ul class="form_items" ID="radioList" runat="server" clientidmode="Static">
</ul>
In Regions.ascx.cs
foreach (var region in Config.ConfigString("str_Regions").Split(','))
{
HtmlGenericControl li = new HtmlGenericControl("li");
RadioButton regionRadio = new RadioButton();
regionRadio.Text = region;
regionRadio.ID = "Radio"+(i++).ToString();
regionRadio.Attributes.Add("name", "region");
regionRadio.Attributes.Add("value", region);
regionRadio.TextAlign = TextAlign.Right;
li.Controls.Add(regionRadio);
radioList.Controls.Add(li);
}
A lot of extra HTML tags are appearing which I don't want. I am getting output as:
<ul id="radioList" class="form_items">
<li>
<span name="region"><input id="MainContent_contactUs_Radio1" type="radio" name="ctl00$MainContent$contactUs$Radio1" value="Australia">
<label for="MainContent_contactUs_Radio1">Australia</label>
</span>
</li>
<li>
<span name="region"><input id="MainContent_contactUs_Radio2" type="radio" name="ctl00$MainContent$contactUs$Radio2" value="America">
<label for="MainContent_contactUs_Radio2">America</label>
</span>
</li>
</ul>
The label under which the 'Australia/America' is coming causes the wrong look by inheriting the styles aligned to all labels.
While I just want
<ul id="radioList" class="form_items">
<li><input id="MainContent_contactUs_Radio1" type="radio" name="ctl00$MainContent$contactUs$Radio1" value="Australia">"Australia"</li><li><input id="MainContent_contactUs_Radio2" type="radio" name="ctl00$MainContent$contactUs$Radio2" value="America">"America"</li></ul>
If you are using System.Web.UI.Webcontrols it will render your control with span. You can see why its rendering between span.
Why does ASP.Net RadioButton and CheckBox render inside a Span?
There two ways to overcome this. First you need to add attribute to input controls not span right now when you directly add attribute it will do that way.
See my blog post about it- http://www.dotnetjalps.com/2014/04/aspnet-checkbox-button-attributes-javascript.html
You need to add attribute like below.
myCheckBox.InputAttributes.Add("onblur", "onBlur();");
For text align and other stuff I suggest you use System.Web.UI.HtmlControls where you can use HtmlInputRadioButton instead of System.Web.UI.Webcontrols radio button. Here you can also manage all HTML attribute very easily.
Another thing you can do like adding labels and HTMLInputRadioButton separately and add class to your label as per your requirement.
string[] regions = {"Autralia", "Asia", "US"};
foreach (var region in regions)
{
HtmlGenericControl li = new HtmlGenericControl("li");
HtmlInputRadioButton radioButton=new HtmlInputRadioButton
{Value = region,
Name = region};
li.Controls.Add(radioButton);
Label label=new Label {Text = region, CssClass = "YourCSSClass"};
li.Controls.Add(label);
radioList.Controls.Add(li);
}
Hopefully this have more controls on css style
I think text-align set the horizontal position of your radio button in its container.
so, check if your container does or not wrap to your radio button.

Get append control value from code behind in ASP.NET

I have a div that contains multiple hidden field which generate by using jquery .append()
function add(ctr)
{
$('.divContainer').append(ctr.clone());
}
In the client side i will have something like
<div class="divContainer">
<div class="dynamicCtr">
<input type="hidden" name="hf_1" id="_1" value="4515">
</div>
<div class="dynamicCtr">
<input type="hidden" name="hf_2" id="_2" value="4422">
</div>
</div>
All the controls inside divContainer are clone by using jquery.
I tried below but doesn't work.
HtmlControl divHave = this.divHave;
foreach (Control control in divHave.Controls)
{
if (control is HtmlInputHidden)
{
HtmlInputHidden hf = (HtmlInputHidden)control;
Response.Write("Value :" + hf.Value);
}
}
Is there any way i can access all the hidden field within the divContainer from code behind?
When you postback, every cloned divs by jquery are lost by server.
Try to use
<asp:Panel ID="divHave" runat="server">
<!-- resolves to a DIV -->
</asp:Panel>
And insert div at server side with Ajax
HtmlGenericControl div = HtmlGenericControl("div")
div.Id = "myid";
divHave.Controls.Add(div);

Extract text from a div

I am trying to make a DropDownList using divs and jquery (so that I can style it as I want)...and its working but the problem is I cant get the selected value from the list..
After selection of the option I am copying the selected value into the a div.. and I want to extract this using c# (in .aspx.cs page)... I've tried to do it using string builder and innerHtml(after adding runat="server" to the div).. but it doesn't work ...code is as follows
.aspx Page:
<div class="ddl">
<div id="lowertriangle" class="lowertriangle"></div>
<div id="uppertriangle" class="uppertriangle"></div>
<div id="label" class="labeldiv_dd" runat="server"></div>//***This is the div from which I want to extract value***
<div id="options" class="optionsidv_dd">
<ul id="options_ul">
<li id="0">Select One Option</li>
<li id="1">Option 1</li>
<li id="2">Option 2</li>
<li id="3">Option 3</li>
<li id="4">Option 4</li>
<li id="5">Option 5</li>
</ul>
</div>
</div>
aspx.cs page
Method 1 that I tried:
string sel_text = label.InnerHtml;
display_sel_value.Text = sel_text.ToString();
2nd method:
var sb = new StringBuilder();
label.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
string s = sb.ToString();
Kindly point out my mistakes and help me in this regard(in extracting innerHTML of the div that is).
Thanks
No, putting content in a div won't work.
Your example isn't complete enough to see all that happens, but let's assume that you're in a standard <form>, you're setting the div's inner HTML to a value with Javascript and then you're submitting in the standard way.
Then one way to do what you want is to use a hidden input and setting its value attribute instead of its contents.
<input id="label" class="labeldiv_dd" runat="server" type="hidden">
In the codebehind, the C# can retrieve the value from this control after submitting with the .Value property.
Ok guys thx for your replies..I found a way around the problem...I used HiddenField control to store the selected value using jQuery like so
$("#options_ul li").click(function () {
var text = this.innerHTML;
***$('#<%= selectedvalue.ClientID %>').val(text);***
$("#options_ul li").css("background-color", "#c2c2c2");
$(this).css("background-color", "white");
//var prev = this.id;
//document.getElementById("label").innerHTML = text;
toggleHeight();
});
and then accessed it server side using
selectedvalue.value;
PS: "selectedvalue" is id of the hiddenfield control

How to incrementally reveal div tags

I have collection of div tags in the form tag, like this:
<form ...>
<div id="div1"> ... </div>
<div id="div2"> ... </div>
...
...
</form>
I want to display only div1 in the visible area than when user presses next, the next div tag i.e. div2 is displayed, and so on.
How can I achieve this?
I don't have much knowledge about different approaches available to do this, but I have some knowledge of Javascript, so any idea will be appreciated.
P.S. please provide sample code if possible, also I want client-side scripting.
Here's some javascript and html demonstration that may help. Increment a current integer. You could deincrement with -- for back as well. There are many ways to do this. This is just one I thought of.
<img src="mynextbutton.jpg" onclick="showNext()" />
<form ...>
<div id="Div0" style="display:inherit;"> ... </div>
<div id="Div1" style="display:none;"> ... </div>
<div id="Div2" style="display:none;"> ... </div>
...
...
</form>
//---------------------------------------------------
var currentDiv = 0;
function showNext()
{
document.getElementById("Div"+currentDiv).style.display = "none";
currentDiv ++;
document.getElementById("Div"+currentDiv).style.display = "ihherit";
}
If you put all of the element IDs into an array, and then use that to get the next item you can remove the dependence on the ID numbering determining the order that they rotate in, and also prevent them from needing to follow such a rigid format.
//add all element IDs to this array
var elements = ["firstElementID","div2","someConentsID","lastElementID"];
var currentIndex = 0;
//ensure that the first item is visible at the start.
function next()
{
//hide current item.
document.getElementById(elements[currentIndex]).Style = "display:none";
//move up the current index by one, wrapping so as to stay within array bounds.
currentIndex = (currentIndex + 1) % elements.length;
//show the new current item.
document.getElementById(elements[currentIndex]).Style = "display:inline";
}
You can adjust the show/hide code to use JQuery, or whatever other mechanism you want.

Generating a POST request for PayPal button in C# ASP.net

I'm trying to allow a web form to use a PayPal buy it now.
The relevant page is here.
Based on which radio button a user selects, depends on which paypal button they are "redirected" to.
The subscriptions are easy - they are just a simple redirect.
The last option, requires a user select a venue.
For this, i require to use the form below:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="10956105">
<table>
<tr><td><input type="hidden" name="on0" value="Venue">Venue</td></tr><tr><td>
<input type="text" name="os0" maxlength="60"></td></tr>
</table>
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
But of course, I want to do it without using that form.
What I have so far is:
if (singleOneOff.Checked)
{
paypalForm.Text = getPaypalForm(venueSelect.SelectedItem.Text);
var strJS = getPayPalPostJS("_xclick");
paypalJs.Text = strJS;
var xxx = "dd";
}
This determines if that particular radio button was ticked.
getPaypalForm
private String getPaypalForm(string venue)
{
StringBuilder strForm = new StringBuilder();
strForm.Append(#"<form action=""https://www.paypal.com/cgi-bin/webscr"" name=""_xclick"" method=""post"">");
strForm.Append(#"<input type=""hidden"" name=""cmd"" value=""_s-xclick"">");
strForm.Append(#"<input type=""hidden"" name=""hosted_button_id"" value=""10956105"">");
strForm.Append(#"<input type=""hidden"" name=""on0"" value=""Venue"">");
strForm.Append(#"<input type=""text"" name=""os0"" value=""{0}"" maxlength=""60"">");
strForm.Append("</form>");
return String.Format(strForm.ToString(), venue);
}
getPayPalPostJS
private String getPayPalPostJS(string strFormId)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var paypalForm = document.forms.namedItem('{0}');");
strScript.Append("paypalForm.submit();");
strScript.Append("</script>");
return String.Format(strScript.ToString(), strFormId);
}
However, if i select the radio button, and a venue, and press the button, nothing happens....
Any ideas where i've gone wrong?
I followed this guide: http://www.netomatix.com/development/postrequestform.aspx
Here's a much cleaner, server-side solution to the ASP.NET/PayPal single form problem:
http://codersbarn.com/post/2008/03/08/Solution-to-ASPNET-Form-PayPal-Problem.aspx
The root of the problem is that ASP.Net web forms wrap everything on the page inside of one large <form> tag. Your paypal code is rendering a nested form and that doesn't work.
Read this question for more information.

Categories