Submit Javascript variable PLUS form data to ASP.NET - c#

I have this code:
var myArray = new Array();
var counter = 0;
function addElementToForm(value){
counter ++;
if (counter < 10)
{
$("#cheese").append(value + '<input type="number" value="0"><br />');
myArray.push(counter + value);
}
};
I have an ASP.NET form on the same page, in the same action of the sumbit button for the form, I want to be able to access myArray from the codefile as well!!

Take a hidden control and make it as runat="server" and try to keep the array value in the hidden control and access it from the codebehind file.

Related

ASP.NET C# JQueryUI How to save index of accordion in a dynamically created user control?

ASP.NET C# JQueryUI How to save index of accordion in a dynamically created user control?
I have a JQueryUI accordion inside a user control , which is dynamically created n times (based on a chosen number inside a ComboBox) from the main aspx page.
I have been using the following javascript code to save the index of accordions that occur once in the main aspx page, I have this once per accordion Control:
var activeAccordion1Item = document.getElementById("<%= HFaccordion1.ClientID %>");
var activeAccordion1 = 0;
if (activeAccordion1Item) {
activeAccordion1 = parseInt(activeAccordion1Item.value);
}
$("#accordion1").accordion({
collapsible: true,
heightStyle: "content",
active: activeAccordion1,
activate: function (event, ui) {
var i = $("#accordion1").accordion("option", "active");
var activeAccordion1Item = document.getElementById("<%= HFaccordion1.ClientID %>");
activeAccordion1Item.value = i;
}
});
And in aspx file:
<asp:HiddenField ID="HFaccordion1" runat="server" Value="0" />
I used this same approach for the one inside the user_control that can happen many times, and it also works, BUT the saved index is always the one from the first accordion, and that is shared among the rest.
So, if I have index 2 in accordion1, and index 1 in accordion2, and a control causes postback, after the postback, both accordion1 and accordion2 appear with index 2 active.
How can I modify the above code to work for the dynamically created accordions independently of each other?
You should change $("#accordion1").accordion to $(".acc").accordion. .acc is class of accordions for this example. You used $("#accordion1") that this worked with active accordion1.
Edit
You need save active accordions in a array (accordionsActivate) when click on each accordion and for getting this array, store array in hidden field (HFaccordions) like this:
<script>
var accordionsActivate = [];
$(document).ready(function () {
var $accordions = $(".acc").accordion({
collapsible: true
, active: false
, icons: false
}).on('click', function () {
if ($.inArray($(this).attr('id'), accordionsActivate) < 0) {
accordionsActivate.push($(this).attr('id'));
$('#<%=this.HFaccordions.ClientID%>').val(accordionsActivate.join());
}
else {
accordionsActivate.splice($.inArray($(this).attr('id'), accordionsActivate), 1);
$('#<%=this.HFaccordions.ClientID%>').val(accordionsActivate.join());
}
});
activeAccodions(); // Active accodions after postback
});
function activeAccodions() {
if ($('#<%=this.HFaccordions.ClientID%>').val() === "")
return;
activeAccardions = $('#<%=this.HFaccordions.ClientID%>').val().split(',');
for (var i = 0; i < activeAccardions.length; i++) {
accordionsActivate.push(activeAccardions[i]);
}
for (var i = 0; i < accordionsActivate.length; i++) {
$('#' + accordionsActivate[i]).accordion("option", "active", 0);
}
}
</script>
Online demo (fiddle)

How to implement timer in asp.net c#?

I want to implement a timer in asp.net web in which, after a time period, the text of a button is changed. I created the button dynamically in gridview and tried this code:
protected void Timer2_Tick(object sender, EventArgs e)
{
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString();
for(int i = 0; i< rowcount; i++)
{
Button button = new Button();
if (button.Text == "requested")
{
button.Text = "available";
}
}
}
But it doesn't work. How can I solve this problem?
This requires client code (JavaScript) that executes on the browser after the page is loaded. ASP.NET generates the page, sends it to the browser, and then the server is done with it until it gets another request. Even if you create a timer in your code-behind, that code-behind is a class that goes out of scope and disappears once the server is done processing the request.
In its simplest form, it would look something like this:
<script>
window.setTimeout(function()
{
//do something
}, 10000); //interval in milliseconds - this is 10 seconds.
<script>
In order to be able to change text, you'll need to make sure that your control has an ID that you can find using JavaScript. Usually whatever ID you use for a server control, ASP.NET is going to modify it somewhat. I'm oversimplifying this, but generally you can do this:
<asp:Label ID="myLabelId" ClientIDMode="Static" Text="The label text"></asp:Label>
or
<div runat="Server" ID="MyLabelId" ClientIDMode="Static">The label text</div>
ClientIdMode="Static" means that when the control is rendered to the page it won't modify the ID.
Then your script might look like this:
<script>
window.setTimeout(function()
{
var label = document.getElementById("MyLabelId");
label.textContent = "The new value";
}, 10000);
<script>
Or instead of using ClientIDMode="Static" you could try this in your script:
var label = document.getElementById("<%= MyLabelId.ClientID %>");
.ClientID is whatever ID the page assigns to the control. This tells it that whatever ID it assigns to that control, to write it directly into your script.

checkbox status lost after update panel works

I have an update panel, which fires every third seconds. I have this code into my asp.net page
<div ID="campaignDiv" runat="server" >
<ul>
</ul>
</div>
and I add its content dynamically like this:
private string CreateLiCheckbox(string checkBoxText)
{
return string.Format("<li><span class=\"textDropdown\">{0}</span><input id=\"{1}\" value=\"{0}\" type=\"checkbox\"><label for=\"{1}\"></label></li>", checkBoxText, checkBoxText + "dropdownID");
}
if (!IsPostBack) {
List<string> comps = getCompainNames();
string html = "<ul>";
for (int i = 0; i < comps.Count(); i++) {
html = html + CreateLiCheckbox(comps[i]);
}
html = html + "</ul>";
campaignDiv.InnerHtml = html;
}
My problem
when the page loads, the checkboxes are like this:
Then, I change the values to these:
but when the update pannel works, the page returns to its default statues, where nothing of the checkboxes are selected
could you help please?

Dynamically add checkboxes to asp.net

I am trying to add Checkboxes dynamically to webpage
string[] words = masg.Split('~');
int size = words.Length;
CheckBox[] cbl = new CheckBox[size];
for (int i = 0; i < words.Length; i++)
{
cbl[i] = new CheckBox();
cbl[i].Text = words[i].ToString();
this.Controls.Add(cbl[i]);
// Response.Write("\n" + words[i]);
}
I am getting error
Control 'ctl01' of type 'CheckBox' must be placed inside a form tag with runat=server.
How should I proceed ? What changes to make on aspx page ? Please help.
You should change it to add in form, because this is referencing your Page. and any server control which you are creating programmatic or by adding on page with runat="server" should place inside a form tag.
like
this.Form.Controls.Add(cbl[i]);
or place a placeholder or panel on the form. and than you can add in it
like
placeholder1.Controls.Add(cbl[i]);
If your .aspx does not contain a form tag, then you should place a form tag there
like
<form runat="server" id="form1">
//Other mark up or server controls.
</form>
hi you need to add a parent control like Panel on your form and then add your check box controls to that panel
string[] words = masg.Split('~');
int size = words.Length;
CheckBox[] cbl = new CheckBox[size];
for (int i = 0; i < words.Length; i++)
{
cbl[i] = new CheckBox();
cbl[i].Text = words[i].ToString();
pnlControls.Controls.Add(cbl[i]);
// Response.Write("\n" + words[i]);
}
Add the a panle control in your aspx page :
<asp:Panel ID="pnlControls" runat="server" >

C# form with Javascript

I have the following Javascript code that creates multiple textboxes depending on the number you enter.
function generate() {
var tot = document.getElementById("nrintrebari").value;
var tbl = document.getElementById("sim");
for (var i = 1; i <= tot; i++) {
tbl.innerHTML = tbl.innerHTML + 'Intrebare nr.' + i + ' <input type="text" size = "80" maxlength= "200" name="intrebare[]" style="height:30px; background-color:#B8B8B8; " > <br><br><br> ';
}
}
How can I loop through this form to get all the answers in the textboxes using C#?
Regardless of Webforms or MVC, when a a form is submitted, it will contain all of the fields in the form post data.
You have chosen to dynamically inject N number of elements all with the same name, "Intrebare[]".
When you do this, the form post data will contain one element (actually a key-value pair) called "Intrebare[]", and it will contain all of the values of your dynamically injected textboxes, separated by commas.
I've put together a very small sample of code that should help you get what you need; actually my code sample iterates through the entire form post so you can see all the fields:
First, I created an empty ASP.net Web Forms Application.
<script type="text/javascript">
function generate() {
var tot = document.getElementById("nrintrebari").value;
var tbl = document.getElementById("sim");
for (var i = 1; i <= tot; i++) {
tbl.innerHTML = tbl.innerHTML + 'Intrebare nr.' + i + ' <input type="text" size = "80" maxlength= "200" name="intrebare[]" style="height:30px; background-color:#B8B8B8; " > <br><br><br> ';
}
}
</script>
<input id="nrintrebari" type="text" value="10" />
<div id="sim">
</div>
<input type="submit" value="submit" />
Result:
<asp:Label ID="TestResultLabel" runat="server" />
<script type="text/javascript">
generate();
</script>
When the user clicks the "submit" button, the form will post with all of the dynamic textboxes included - I chose 10 for sanity...
Here is what the code looks like to go through the form collection on the code-behind:
using System;
using System.Web;
using System.Text;
namespace StackOverflow.Web.LoopThroughForm
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
GetFormElements();
}
}
private void GetFormElements()
{
// HttpContext object contains information of the current request,
// and the Form object contains all of the submitted form elements
var form = HttpContext.Current.Request.Form;
StringBuilder sb = new StringBuilder();
string resultFormat = "<div>Element: {0} - Value: {1}";
for (int i = 0; i < form.Count; i++)
{
sb.AppendFormat(resultFormat, form.Keys[i], form[i]);
}
TestResultLabel.Text = sb.ToString();
}
}
}
This will include ALL form fields, including the ViewState field;
From here you have many options, you can hardcode the "Intrebare[]" field and only get that one, and split the result by a comma:
private void GetIntrebare()
{
var form = HttpContext.Current.Request.Form;
StringBuilder sb = new StringBuilder();
sb.Append("<div>Intrebare Values: <br />");
for (int i = 0; i < form.Count; i++)
{
if (form.Keys[i] == "intrebare[]")
{
string valuesFormat = "Value {0} : {1} <br />";
string[] values = form[i].Split(',');
for (int ii = 0; ii < values.Length; ii++)
{
// Label the value index + 1 to match the 'actual' dynamic textbox
sb.AppendFormat(valuesFormat, ii + 1, values[ii]);
}
}
}
sb.Append("</div>");
TestResultLabel.Text = sb.ToString();
}
I hope this helps to get you going with retrieving values form form/post data. FWIW, I believe MVC is the same - Controllers should also have the HttpContext object available that will contain all of this data, because under the hood, HTTP POST/GET does not care if you are using Java, .net, MVC, or whatever in order to read the values submitted by a user.
when you render your input fields give a certain class to those for example question this will also give you the advantage to style all of them at once but most important you can then use JQuery to get all and only the controls with that class question assigned.
see her for the JQuery class selector example:
http://api.jquery.com/class-selector/
if you then want to get these controls server side via C# I imagine the FindControl of web forms would not work since these controls are not server controls but simple html ones. I would try to use the HTML Agility Pack to parse the page, but at postback you should make sure the controls are created again and their values are preserved.
Personally I would loop client side using the JQuery approach and send server side the values using an Ajax PageMethod or similar approach.

Categories

Resources