Im having a javascript code wherein im accessing div in aspx page using innerHTML attribute and want to do following: 1) Get entire content of that div tag.
2) Bind the entire contents of that div tag to a variable say res .
3) Give the value in res to a hidden control in aspx page and finally
4) Render that value from hidden field and use it in aspx.cs code behind.
My aspx page is as below
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type ="text/javascript" language = "javascript">
function inject()
{
var res = document.getElementById('<%= div.ClientID %>').innerHTML.toString();
document.getElementById('hidden1').value = res;
}
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Button ID="BtnAdd" runat="server" Text="Add" onclick="BtnAdd_Click" Width="67px" />
<div id = "div" runat ="server">
</div>
<input type = "hidden" id = "hidden1" value = "" />
<asp:Label ID = "lbl" Text = "Final answer goes here" runat = "server"/>
</asp:Content>
and the code behind to access it as as follows
public partial class _Default : System.Web.UI.Page
{
public string str = "* is the capital of *";
StringBuilder sb = new StringBuilder();
public static int count = 1;
public string res;
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder htm = new StringBuilder();
for (int j = 0; j < str.Length; j++)
{
if (str[j] == '*')
{
string res = "<input type = 'text' id ='" + count + "' value = ''/>";
htm = htm.Append(res);
count++;
}
else
{
htm = htm.Append(str[j]);
}
}
div.InnerHtml = htm.ToString();
}
protected void BtnAdd_Click(object sender, EventArgs e)
{
this.Page.RegisterStartupScript("<Script>", "<Script type='text/javascript'> inject();</Script>");
string res = Request.Form["hidden1"];
lbl.Text = res;
}
}
Now code is executing but im not getting the entire content from the innerHTML thing onto res variable in the code behind. By entire content i mean everything within to tag. Im sure i have messed it somewhere or if its an wrong approach can i be suggested a better way??
Thanks for taking time onto this
Related
Below is my code which gives the word count on button click,but instead of displaying word count on button click i need to display word count directly when i am typing in ck editor.How can i do this.I am able get the count on button click but i need the same count to be displayed while typing
HTML code:
<body>
<form id="form1" runat="server">
<div>
<CKEditor:CKEditorControl ID="CKEditor1" BasePath="/ckeditor/" runat="server">
</CKEditor:CKEditorControl>
<asp:Button ID="btn1" runat="server" OnClick="btn1_Click" Text="Get Word Count" />
<asp:Label ID="lbl1" runat="server"></asp:Label>
</div>
</form>
</body>
C# code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn1_Click(object sender, EventArgs e)
{
string whole_text = CKEditor1.Text;
string trimmed_text = whole_text.Trim();
// new line split here
string[] lines = trimmed_text.Split(Environment.NewLine.ToCharArray());
// don't need this here now...
//string[] split_text = trimmed_text.Split(' ');
int space_count = 0;
string new_text = "";
foreach (string line in lines)
{
// Modify the inner foreach to do the split on ' ' here
// instead of split_text
foreach (string av in line.Split(' '))
{
if (av == "")
{
space_count++;
}
else
{
new_text = new_text + av + ",";
}
}
}
new_text = new_text.TrimEnd(',');
// use lines here instead of split_text
lines = new_text.Split(',');
You need add event handler to CK Editor.
Example from documentation:
var editor = CKEDITOR.replace( 'editor1' );
// The "change" event is fired whenever a change is made in the editor.
editor.on( 'change', function( evt ) {
// getData() returns CKEditor's HTML content.
console.log( 'Total bytes: ' + evt.editor.getData().length );
});
For more info http://docs.ckeditor.com/#!/guide/dev_savedata
I'm new to coding, hope some can help me a bit, I got stuck at retrieving data from my Dynamically added Text boxes in ASP.NET.
I Master Site and a Content site. I have added some buttons to the content site there are adding or removing the textboxes, after what's needed by the user.
My problem is, that i'm not sure how to retrieve the data correct. hope some body can help me on the way.
My Content site:
<%# Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="CreateRMA.aspx.cs" Inherits="CreateRMA" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainsite" Runat="Server">
<div id="div_fortext" class="div_fortext">
<p class="header2">
Opret RMA Sag
</p>
<p class="text1">
Her Kan de oprette alt det udstyr der skal sendes til reperation hos zenitel.
</p>
</div>
<div id="div_insert_devices" runat="server">
</div>
// 3 buttons one who add, one who remove textboxes and a submit button
<asp:Button ID="btnAddRow" runat="server" Text="Add Row" CssClass="butten1" OnClick="btnAddRow_Click" />
<asp:Button ID="btnRemoveRow" runat="server" Text="Remove Row" CssClass="butten1" OnClick="btnRemoveRow_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="butten1" OnClick="btnSubmit_Click" />
</asp:Content>
My C# code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateRMA : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["DeviceCount"] = ViewState["DeviceCount"] == null ? 1 : ViewState["DeviceCount"];
InsertLine();
}
}
private void InsertLine()
{
int DeviceCount = int.Parse(ViewState["DeviceCount"].ToString());
for (int i = 0; i < DeviceCount; i++)
{
LiteralControl text = new LiteralControl("<div class=\"divPerDevice\">");
div_insert_devices.Controls.Add(text);
TextBox txtbox = new TextBox();
txtbox.ID = "serial" + i;
txtbox.CssClass = "textbox1";
txtbox.Attributes.Add("runat", "Server");
div_insert_devices.Controls.Add(txtbox);
text = new LiteralControl("</div>");
div_insert_devices.Controls.Add(text);
}
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
int count = int.Parse(ViewState["DeviceCount"].ToString());
count++;
ViewState["DeviceCount"] = count;
InsertLine();
}
protected void btnRemoveRow_Click(object sender, EventArgs e)
{
int count = int.Parse(ViewState["DeviceCount"].ToString());
count--;
ViewState["DeviceCount"] = count;
InsertLine();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Submit - save the textboxes to Strings ??? Can any body help
}
}
((TextBox)div_insert_devices.FindControl("txtboxname")).Text
Try this one
you can use the following code
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Submit - save the textboxes to Strings ??? Can any body help
int DeviceCount = int.Parse(ViewState["DeviceCount"].ToString());
for (int i = 0; i < DeviceCount; i++)
{
TextBox txtbx= (TextBox)div_insert_devices.FindControl("serial" + i);
if(txtbx!=null)
{
var value= txtbx.Text;
}
}
}
The way i would attempt this is like the following:
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (Control control in div_insert_devices.Controls){
if (control.GetType() == typeof(textbox)){
Textbox myDynTextbox = (Textbox)control;
Var myString = myDynTextbox.Text;
Please note this code can be simplyfied further but, i have written it this was so you understand how it would work, and my advise would be to store all the strings in a collection of Strings, making it easier to maintain.
}
}
}
Kush
Why don't you use javascript to save the value of textbox. just hold the value in some hidden field and bind it everytime when you need it.
Hi I found the solution after some time here... I did not got any of examples to work that you have provided. sorry.
But I almost started from scratch and got this to work precis as I wanted :)
My Content Site:
<%# Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="CreateRMA.aspx.cs" Inherits="CreateRMA" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainsite" Runat="Server">
<div id="div_fortext" class="div_fortext">
<p class="header2">
Opret RMA Sag
</p>
<p class="text1">
Some TEXT
</p>
</div>
</div>
<asp:Button ID="btnAddRow" runat="server" Text="Add Row" CssClass="butten1" OnClick="btnAddRow_Click" />
<asp:Button ID="btnRemoveRow" runat="server" Text="Remove Row" CssClass="butten1" OnClick="btnRemoveRow_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="butten1" OnClick="btnSubmit_Click" />--%>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:PlaceHolder runat="server" id="DynamicDevices"></asp:PlaceHolder>
<asp:Button id="btnAddTextBox" runat="server" text="Tilføj" CssClass="butten1" OnClick="btnAddTextBox_Click" />
<asp:Button id="btnRemoveTextBox" runat="server" text="Fjern" CssClass="butten1" OnClick="btnRemoveTextBox_Click" />
<asp:Button runat="server" id="Submit" text="Submit" CssClass="butten1" OnClick="Submit_Click" />
<br /><asp:Label runat="server" id="MyLabel"></asp:Label>
</asp:Content>
My C# code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateRMA : System.Web.UI.Page
{
static int myCount = 1;
private TextBox[] dynamicTextBoxes;
private TextBox[] Serial_arr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
myCount = 1;
}
}
protected void Page_Init(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
if (myControl != null)
{
if (myControl.ID.ToString() == "btnAddTextBox")
{
myCount = myCount >= 30 ? 30 : myCount + 1;
}
if (myControl.ID.ToString() == "btnRemoveTextBox")
{
myCount = myCount <= 1 ? 1 : myCount - 1;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
dynamicTextBoxes = new TextBox[myCount];
Serial_arr = new TextBox[myCount];
int i;
for (i = 0; i < myCount; i += 1)
{
LiteralControl literalBreak = new LiteralControl("<div>");
DynamicDevices.Controls.Add(literalBreak);
TextBox Serial = new TextBox();
Serial.ID = "txtSerial" + i.ToString();
Serial.CssClass = "";
DynamicDevices.Controls.Add(Serial);
Serial_arr[i] = Serial;
TextBox textBox = new TextBox();
textBox.ID = "myTextBox" + i.ToString();
DynamicDevices.Controls.Add(textBox);
dynamicTextBoxes[i] = textBox;
literalBreak = new LiteralControl("</div>");
DynamicDevices.Controls.Add(literalBreak);
}
}
public static Control GetPostBackControl(Page thePage)
{
Control mycontrol = null;
string ctrlname = thePage.Request.Params.Get("_EVENTTARGET");
if (((ctrlname != null) & (ctrlname != string.Empty)))
{
mycontrol = thePage.FindControl(ctrlname);
}
else
{
foreach (string item in thePage.Request.Form)
{
Control c = thePage.FindControl(item);
if (((c) is System.Web.UI.WebControls.Button))
{
mycontrol = c;
}
}
}
return mycontrol;
}
protected void Submit_Click(object sender, EventArgs e)
{
int deviceCount = Serial_arr.Count();
DataSet ds = new DataSet();
ds.Tables.Add("Devices");
ds.Tables["Devices"].Columns.Add("Serial", System.Type.GetType("System.String"));
ds.Tables["Devices"].Columns.Add("text", System.Type.GetType("System.String"));
for (int x = 0; x < deviceCount; x++)
{
DataRow dr = ds.Tables["Devices"].NewRow();
dr["Serial"] = Serial_arr[x].Text.ToString();
dr["text"] = dynamicTextBoxes[x].Text.ToString();
ds.Tables["Devices"].Rows.Add(dr);
}
//MyLabel.Text = "der er " + deviceCount +" Devices<br />";
//foreach (TextBox tb in Serial_arr)
//{
// MyLabel.Text += tb.Text + " :: ";
//}
//MyLabel.Text += "<br />";
//foreach (TextBox tb in dynamicTextBoxes)
//{
// MyLabel.Text += tb.Text + " :: ";
//}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
}
protected void btnRemoveTextBox_Click(object sender, EventArgs e)
{
}
}
Thanks For all the help anyway :)
Hope somebody can use this.
Best regards Kasper :)
I need to make the asp button to not refresh the whole page when I click it.
my code is just to make a picture change to another picture but the index of the picture is set in the page load method. And every time you click the button to go to the next picture index, the whole page refreshes and calls the page load method. That then sets the index back to 0.
how can I make the page stop calling the page load method when I click a button
Here's the basic code I'm using
in a table:
<tr>
<td> <asp:Button ID="Button1" runat="server" Text="Prev" OnClick="Button1_Click" OnClientClick="return false"/> </td>
<td> <img ID="pic" alt="" src="010.JPG" runat="server" width="200" height="200" /> </td>
<td> <asp:Button ID="Button2" runat="server" Text="Next" OnClick="Button2_Click" OnClientClick="return false"/> </td>
</tr>
and this is the .cs file
private List<String> imagePathList = new List<String> { };
private List<Boolean> isActivePath = new List<Boolean> { };
protected void Page_Load(object sender, EventArgs e)
{
Debug.WriteLine("GALLARY *page load*");
pic.Width = 200;
pic.Height = 200;
addToList();
getImagePath(1);
}
protected void Button1_Click(object sender, EventArgs e)
{
Debug.WriteLine("GALLARY *Button1_Click*");
int index = getActive();
getImagePath(index = index - 1);
}
protected void Button2_Click(object sender, EventArgs e)
{
Debug.WriteLine("GALLARY *Button2_Click*");
int index = getActive();
getImagePath(index = index + 1);
}
private void getImagePath(int index)
{
Debug.WriteLine("GALLARY *getImagePath* index = "+index);
int length = imagePathList.Count;
if (index < length && index >= 0)
{
//pic.Src = imagePathList[index];
//pic.Alt = imagePathList[index];
pic.Src = imagePathList[index];
pic.Alt = imagePathList[index];
setActive(index);
}
else
{
pic.Src = "DOES NOT EXIST";
pic.Alt = "DOES NOT EXIST";
}
}
private void addToList()
{
Debug.WriteLine("GALLARY *addToList*");
imagePathList.Clear();
isActivePath.Clear();
addImage("08.JPG");
addImage("09.JPG");
addImage("010.JPG");
addImage("011.JPG");
addImage("012.JPG");
}
private void addImage(String filename)
{
Debug.WriteLine("GALLARY *addImage* filename = "+filename);
imagePathList.Add(filename);
isActivePath.Add(false);
}
private void setActive(int index)
{
Debug.WriteLine("GALLARY *setActive* index = " + index);
for (int i = 0; i > isActivePath.Count; i++)
{
isActivePath[i] = false;
}
isActivePath[index] = true;
}
private int getActive()
{
Debug.Write("GALLARY *getActive*");
int temp = 0;
for (int i = 0; i > isActivePath.Count; i++)
{
if (isActivePath[i] == true)
{
temp = i;
}
}
Debug.WriteLine("index = " + temp);
return temp;
}
You need to use UpdatePanel for Partial Updates.
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always" >
<ContentTemplate>
<asp:Image ID="Image1" runat="server" Height="23px" Width="24px" />
<asp:Button ID="btnImageChange" runat="server" Text="Check" OnClick="btnImageChange_Click1" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnImageChange" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Then in code behind .cs write this:
protected void btnImageChange_Click1(object sender, EventArgs e)
{
// you can add a loop here for the list of images...
Image1.ImageUrl = "~/Images/loading.gif";
}
onClientClick="return false"
That should do it! Onclick will refer to an ASP.net function, onClientClick will render as OnClick on the control in HTML.
on button click call this javascript functon
<script type="text/Javascript">
function ChangeIndex(){
$.ajax({
url: "Url of your page/Methodname",
data: JSON.stringify({variableName,VariableValue}),
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function (data) {
//set your image scr here
},
error: function (data, status, jqXHR) {
//alert('There was an error.');
}
}
</script>
in your code behind write a webmethod
[WebMethod]
public static string Methodname(string variableName)
{
//Logic to get the index.
return "Index";
}
Hope this helps. Please post your code so that I can help you further.
Try not to implement such old fashion buttons. Instead you can use fly buttons or jQuery triggered button which won't post back.
i am working with dynamic TextBoxes and then Getting their Values in code behind file. I am creating these boxes using Javascript. my asp.net page code is
<script type="text/javascript">
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
return false;
});
});
</script>
</head>
<body>
<form id="form2" runat="server">
<h1>jQuery add / remove textbox example</h1>
<asp:TextBox runat="server" ID="txt1" type='text' name="textname" />
<asp:Panel runat="server" ID='TextBoxesGroup'>
</asp:Panel>
<asp:LinkButton ID="addButton" runat="server">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</body>
i have one Textbox shown on the page, which should shows only one values when no dynamic Textbox is created. My C# code is
protected void Button1_Click(object sender, EventArgs e)
{
string name = txt1.Text + ",";
if (TextBoxesGroup.Controls.Count > 0)
{
for (int i = 1; i <= TextBoxesGroup.Controls.Count; i++)
{
name += Request.Form["textbox" + i] + ",";
}
}
Label1.Text = name;
}
on asp:button click it should display all the values separated by (,). but it is only showing top 2 values, one of which is asp:Textbox and second is dynamic Textbox,, i want the values of all the Textboxes created dynamically, and when no dynamic textbox is added it should only show the value from asp:textBox... Thanks in Advance
Html input elements created through javascript on the client, are not going to be in TextBoxesGroup.Controls on the server.
Changes in the client DOM structure have no effect on the Page's Control tree. The only thing affected will be the content of HttpRequest during postback. One way to know how many dynamically created input elements contributed to Request.Form data is to pass this information as part of the request. This is why you will have to go with the hidden field suggestion. The hidden field value will bring back the count of client-side inputs. You have to set it in javascript every time you create a new input, read it in server-side code, convert to integer and use in your for loop.
Add
<asp:HiddenField runat="server" ID="txtDynamicCount" value="0" />
to the the markup inside form tag.
In javascript click event after counter++; line add
$("#txtDynamicCount").val(counter);
In Button1_Click:
int count;
if (!int.TryParse(txtDynamicCount.Value, out count))
count = 0;
for (int i = 1; i <= count; i++)
{
...
}
The important difference from the other answer is that textboxes (input elements) will not persist between form submits.
You cannot populate server controls in client side. Instead, you want to populate them from server. Here is the sample -
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:LinkButton ID="addButton" runat="server" OnClick="btnAdd_Click">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br/>
Posted Results: <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>)ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (int id in ControlIds)
{
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
protected void Button1_Click(object sender, EventArgs e)
{
var ids = ControlIds;
foreach (var id in ids)
{
var textbox = (TextBox)PlaceHolder1.FindControl(id.ToString());
Label1.Text += textbox.Text + ", ";
}
}
Here is code. Its not showing any compile or run time error. I debugged also then till data binding works fine. But then also controls not shown in web page!
Sample.aspx:
<body>
<form id="form1" runat="server">
<asp:PlaceHolder ID="_placeHolder1" runat="server">
</asp:PlaceHolder>
</form>
</body>
Sample.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
_placeHolder1.Controls.Add(CreateReapeater());
}
private Control CreateReapeater()
{
Repeater _repeater1 = new Repeater();
Stack _stack1 = new Stack();
for (int i = 0; i < 7; i++)
{
_stack1.Push(i);
}
_repeater1.DataSource = _stack1;
_repeater1.DataBind();
return _repeater1;
}
Actually repeater have no inbuild column structure as like gridview. so when we bind repeater dynamically we need to also create the item template for that.
You need to modify the createrepeater function as below.
private Control CreateReapeater()
{
Repeater _repeater1 = new Repeater();
Stack _stack1 = new Stack();
for (int i = 0; i < 7; i++)
{
_stack1.Push(i);
}
_repeater1.DataSource = _stack1;
_repeater1.DataBind();
foreach (RepeaterItem repeatItem in _repeater1.Items)
{
int index = repeatItem.ItemIndex;
RepeaterItem repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Item);
Label lbl = new Label();
lbl.Text = "Item No :" + index.ToString() + "<br/>";
repeatItem.Controls.Add(lbl);
}
return _repeater1;
}
This will resolve your issue.
Happy Coding.....