I'm having problems with a chunk of code that's meant to add a textbox to a Repeater in ASP.
I have the following:
<asp:Repeater ID="uxRolesList" runat="server">
<ItemTemplate>
<div id="<%# GetRolesDivId() %>" class="div_row">
<asp:TextBox ID="uxTxtBoxRole" runat="server" rows="5" columns="100" Text='<%# DataBinder.Eval(Container.DataItem, "RequirementDescription") %>' TextMode="multiline" MaxLength="2000"></asp:TextBox>
<input type="button" style="vertical-align:top;" value="X" class="remove-roles-btn" />
<br /><br />
</div>
</ItemTemplate>
</asp:Repeater>
Which generates a load of textboxes that look like this in the html:
<td id="rolesColumn">
<div id="roles-0" class="div_row">
<textarea name="ctl00$mainContent$uxRolesList$ctl00$uxTxtBoxRole" rows="5" cols="100" id="ctl00_mainContent_uxRolesList_ctl00_uxTxtBoxRole">Cool Job1</textarea>
<input type="button" style="vertical-align:top;" value="X" class="remove-roles-btn" />
<br /><br />
</div>
</td>
I've also added the following button, that should add a textbox to this list when hit:
<asp:Button CssClass="btn" ID="uxAddRoleBtn" runat="server" Text="Add a new role requirement" />
Using the following jQuery code:
$("#ctl00_mainContent_uxAddRoleBtn").live("click", (function (e) {
var rolesCounter = $('#ctl00_mainContent_uxTxtBoxRolesCount').val();
if (rolesCounter < 10) {
var rolesCounterText = "0" + rolesCounter;
} else {
var rolesCounterText = rolesCounter;
}
$('#rolesColumn').append("<div id='roles-" + rolesCounter + "' class='div_row'><textarea name='ctl00$mainContent$uxRolesList$ctl" + rolesCounterText + "$uxTxtBoxRole' rows='5' cols='100' id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxTxtBoxRole' MaxLength='2000' ></textarea><input type='submit' name='ctl00$mainContent$uxRolesList$ctl" + rolesCounterText + "$uxRemoveRoleBtn' value='X' id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxRemoveRoleBtn' class='remove-roles-btn' style='vertical-align:top;' /><br /><span id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxValTxtBoxRole' style='color:Red;visibility:hidden;'>Please complete this role requirement</span><br /><br /></div>");
e.preventDefault();
rolesCounter++;
$('#ctl00_mainContent_uxTxtBoxRolesCount').val(rolesCounter);
}));
So far so good. I hit the add button and the textbox appears, I type something in, everything's great. The html look something like this:
<div id="roles-0" class="div_row">
<textarea id="ctl00_mainContent_uxRolesList_ctl00_uxTxtBoxRole" cols="100" rows="5" name="ctl00$mainContent$uxRolesList$ctl00$uxTxtBoxRole">Cool Job1</textarea><input class="remove-roles-btn" type="button" value="X" style="vertical-align:top;"><br><br>
</div>
<div id="roles-1" class="div_row">
<textarea id="ctl00_mainContent_uxRolesList_ctl01_uxTxtBoxRole" maxlength="2000" cols="100" rows="5" name="ctl00$mainContent$uxRolesList$ctl01$uxTxtBoxRole">Test</textarea><input class="remove-roles-btn" type="submit" style="vertical-align:top;" value="X" name="ctl00$mainContent$uxRolesList$ctl01$uxRemoveRoleBtn"><br><br>
</div>
Then I hit submit and the new values do not come through.
In the C# side I'm trying to access the data using:
foreach (RepeaterItem item in dl.Items)
{
System.Web.UI.WebControls.TextBox rb = item.FindControl(control) as System.Web.UI.WebControls.TextBox;
if (rb.Text.Trim() != "")
{
PositionRequirement pr = new PositionRequirement();
pr.RequirementDescription = rb.Text;
pr.RequirementLevel = new PositionRequirementLevel(level, levelDescription);
pr.OrderNumber = i;
i++;
positionRequirements.Add(pr);
}
}
where dl = uxRolesList
control = uxTxtBoxRole
I'm at an utter loss as to why the new values are not coming through with the uxRolesList Repeater.
What am I doing wrong?
from what i know , the approach used is not going to show the items that are added within the Repeater Datasource, unless they exist before the page is being served to the user, so in the example, only the items that were bound to the repeater before leaving the server (if any) will show.
if you don't want to leave the page and make a trip to the server on every add click,of the top my head i would suggest that you would access them via the request Object using the name instead of the id ( Request[""] ) and keep the name of each textbox similar ("txtbox1","txtbox2")and append the count as you did in your Jquery code, then on the server when the page is submitted loop over the items using the counter that you have stored in uxTxtBoxRolesCount.
Related
I am trying to implement Sign Up api of Constant Contact. They gave me this HTML code. Runs properly if i save it as a HTML page.
What i want to do is convert this form to C# code that will execute onClick of a button. The HTML portion is looking fine but today is my first day with ASP.net and i have no idea what code to put in the code-behind .cs file. Searched a lot and am super confused.
This method is clicked when the submit button is clicked:
protected void buttonId_Click(object sender, EventArgs e)
{
}
Here is my ui side code:
<asp:TextBox ID="TextBox3" runat="server" class="name" value="First Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'First Name';}"></asp:TextBox>
<asp:TextBox ID="TextBox4" runat="server" class="name" value="Last Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Last Name';}"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" class="name" value="Join our mailing list" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Join our mailing list';}"></asp:TextBox><br>
<asp:Button id="buttonId" OnClick="buttonId_Click" class="btn btn-info sub1" runat="server" Text="SUBSCRIBE">
</asp:Button>
Here is the HTML code that i got from constant contact:
<form data-id="embedded_signup:form" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup">
<p>Sign up to get interesting news and updates delivered to your inbox.</p>
<!-- The following code must be included to ensure your sign-up form works properly. -->
<input data-id="ca:input" type="hidden" name="ca" value="my-secrect-key">
<input data-id="list:input" type="hidden" name="list" value="3">
<input data-id="source:input" type="hidden" name="source" value="EFD">
<input data-id="required:input" type="hidden" name="required" value="list,email">
<input data-id="url:input" type="hidden" name="url" value="">
<p data-id="Email Address:p" ><input data-id="Email Address:input" type="text" name="email" value="" maxlength="80"></p>
<p data-id="First Name:p" ><input data-id="First Name:input" type="text" name="first_name" value="" maxlength="50"></p>
<p data-id="Last Name:p" ><input data-id="Last Name:input" type="text" name="last_name" value="" maxlength="50"></p>
<button type="submit" class="Button ctct-button Button--block Button-secondary" data-enabled="enabled">Sign Up</button>
</form>
Here's an example of some code you could put in your button OnClick event. This POST's data to another URL.
Hopefully you can figure out what's going on in this code. Basically it is building a string (data) with all of the data from the HTML form and submitting this to the other website using HTTP POST.
Most likely you would also need to check the response back from the other website.
string remoteUrl = "https://visitor2.constantcontact.com/api/signup";
ASCIIEncoding encoding = new ASCIIEncoding();
string data = "ca=my-secrect-key&list=3&source=EFD&required=list,email&url=&email=" + Server.UrlEncode(TextBox1.Text) + "&first_name=" + Server.UrlEncode(TextBox2.Text) + "&last_name=" + Server.UrlEncode(TextBox3.Text);
byte[] bytes = encoding.GetBytes(data);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(remoteUrl);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = bytes.Length;
using (Stream stream = httpRequest.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
my concern is about post-back. I have 3 textboxes, the last name, first name and username. I want to combine last name and first name to create a username have lastname.firstname format. My code in .aspx is as follows. The post-back is true for first name because after the user enters the first name, it will automatically generate the username.
<strong>LAST NAME: <span style="color: #FF0000">*</span> </strong>
<asp:TextBox ID="txtLname" runat="server"
Width="197px" onkeypress="return Alphabet()" BorderStyle="Solid"></asp:TextBox>
<strong>FIRST NAME: <span style="color: #FF0000">*</span> </strong> <asp:TextBox ID="txtFname" runat="server" Width="199px"
onkeypress="return Alphabet()" AutoPostBack="True"
ontextchanged="txtFname_TextChanged" BorderStyle="Solid"></asp:TextBox>
<strong>USERNAME: </strong> <asp:TextBox
ID="txtUser" runat="server"
Width="225px" ReadOnly="True" style="margin-left: 6px" BorderStyle="Solid" onkeypress="return Alphabet()"></asp:TextBox>
My code in .aspx.cs is as follows.
protected void txtFname_TextChanged(object sender, EventArgs e)
{
string mystring = txtFname.Text;
mystring = Regex.Replace(mystring, #"\s+", "");
txtUser.Text = txtLname.Text + "." + mystring;
}
this is to trigger the automatic generation of username.
To sum it up, I want to know how to stop post-back from going back to the top of the page after entering the first name for automatic generation of username. thank you very much.
Adjust as you need:
<html>
<head></head>
<body>
<form action="">
Last Name :<input id="txtLastName" name="txtLastName" type="text" oninput="updateUserName()"></input><br />
First Name:<input id="txtFirstName" name="txtLastName" type="text" oninput="updateUserName()"></input><br />
Username:<input id="txtUserName" name="txtLastName" type="text" readonly></input><br />
<button type="submit">Submit</button>
</form>
<script>
function updateUserName()
{
var last_name = document.getElementById("txtLastName").value;
var first_name = document.getElementById("txtFirstName").value;
if(last_name !== "" && first_name !== "")
document.getElementById("txtUserName").value = last_name+"."+first_name;
}
</script>
</body>
</html>
I have a Listview which I have used to display messages.Along with each message there is a link to "Reply" message.Since different user can send message to one user.The user have different message from different user.Now i need to track each user who are sending message.I was wondering if there is a way to know which message is selected so that the sender's id can be traced.
Here is my List view.
<asp:ListView ID="msg_list" runat="server">
<ItemTemplate>
<table>
<tr class="myitem">
<td>
<asp:Label role="menuitem" ID="msg_lbl" runat="server" text='<%#Eval("msg")%>' /><i style=" color:Gray; " > from
<asp:Label ID="tme" runat="server" Text='<%#Eval("name")%>' />
<i> on </i>
<asp:Label ID="tmelbl" runat="server" Text='<%#Eval("tme")%>'/>
<a id="msg-reply" class="btn button" data-toggle="modal" data-target="#msg-rply" style="cursor:pointer;" ><i class="glyphicon glyphicon-share-alt white"> </i></a> </td>
<hr style=" margin-top:1px; margin-bottom:1px; " />
</tr>
</table>
<%--<hr style=" margin-top:1px; margin-bottom:1px; " />--%>
</ItemTemplate>
</asp:ListView>
With this list view i display the messages.In the above code you can see this line <a id="msg-reply" class="btn button" data-toggle="modal" data-target="#msg-rply" style="cursor:pointer;" ><i class="glyphicon glyphicon-share-alt white"> </i></a> </td>
So,when I click the icon a lightbox appears(modal of bootstrap) where i can write my message.
This lightbox has a button to send message(insert to database) which is as follows.
public void reply_msg(object sender, EventArgs e)
{
string tym = DateTime.Now.ToString();
string sid = Session["userid"].ToString();
//string rid = ((Label)msg_list.FindControl("easy")).Text;
//Label mr = (Label)msg_list.FindControl("reg_id_reply");
// string rid = mr.Text;
string rid = Session["msgreply"].ToString();
//msg_list.Items.FindControl("easy");
sc.connection();
SqlCommand cmd = new SqlCommand("insert into message(msg,senderId,receiverId,tme) values( #msg,#sid,#rid,#tme) ", sc.con);
cmd.Parameters.AddWithValue("#msg", ReplyMsgTb.Text);
cmd.Parameters.AddWithValue("#sid", sid);
cmd.Parameters.AddWithValue("#rid", rid);
cmd.Parameters.AddWithValue("#tme", tym);
cmd.ExecuteNonQuery();
sc.con.Dispose();
sc.con.Close();
}
What i need is to know which item of ListView is selected when i click the icon that brings out the lightbox to send message.
OR is there any other way to know which item of Listview is selected.
You can use check box with every row. So when the user checks the check box for the particular row you can easily reply to the selected user.
your code will be something like this:-
<asp:ListView ID="msg_list" runat="server">
<ItemTemplate>
<table>
<tr class="myitem">
<td>
<asp:TemplateField HeaderText="Id" ItemStyle-HorizontalAlign="Left">
<ItemTemplate >
<asp:CheckBox ID="chkRow" onclick ="CheckSingleCheckbox(this)" AutoPostBack="true" runat="server" OnCheckedChanged="chkRow_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:Label role="menuitem" ID="msg_lbl" runat="server" text='<%#Eval("msg")%>' /><i style=" color:Gray; " > from
<asp:Label ID="tme" runat="server" Text='<%#Eval("name")%>' />
<i> on </i>
<asp:Label ID="tmelbl" runat="server" Text='<%#Eval("tme")%>'/>
<a id="msg-reply" class="btn button" data-toggle="modal" data-target="#msg-rply" style="cursor:pointer;" ><i class="glyphicon glyphicon-share-alt white"> </i></a> </td>
<hr style=" margin-top:1px; margin-bottom:1px; " />
</tr>
</table>
<%--<hr style=" margin-top:1px; margin-bottom:1px; " />--%>
you can use the script given below for finding which check box has been checked:-
<script type="text/javascript">
function CheckSingleCheckbox(ob) {
var grid = ob.parentNode.parentNode.parentNode;
var inputs = grid.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (ob.checked && inputs[i] != ob && inputs[i].checked) {
inputs[i].checked = false;
}
}
}
}
</script>
I have this FileUpload control that automatically adds a FileUpload Control. But I need to have it also create an RegularExpressionValidator. Not sure how I can do this.
Any ideas?
<script type = "text/javascript">
var counter = 0;
function AddFileUpload() {
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
function RemoveFileUpload(div) {
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
</script>
<div id="FileUploadContainer">
<asp:FileUpload ID="FileUpload1" runat="server" />
<!--FileUpload Controls will be added here -->
</div>
<br />
<input id="Button1" onclick="AddFileUpload()" style="height: 27px; width: 150px;" tabindex="25" type="button" value="Add More Attachments" />
<asp:RegularExpressionValidator ID="rexp" runat="server" ControlToValidate="FileUpload1"
ErrorMessage="Only .pdf, .jpg"
ValidationExpression="(.*\.([Pp][Dd][Ff])|.*\.([Jj][Pp][Gg])$)">
</asp:RegularExpressionValidator>
Probably you could try this way:
Always initiate Regular Expression Validator in the page along with the control.
Make the Regular Expression Validation disable through javascript and make the control's display to none if you don't need the control
presence in the UI.
Make the Regular Expression Validation enable through javascript and make the control's to be appeared if you need the control presence
in the UI.
Good Reference to read for this:
http://msdn.microsoft.com/en-us/library/aa479045.aspx
I have a div with style="display:none". The div should become visible on pressing an html button:
function JSAdd() {
document.getElementById('divDetail').style.display = "block";
}
<div style="float:left">
<div id="ctl00_MainContent_upnlLbRD">
<select size="4" name="ctl00$MainContent$lbRD" id="ctl00_MainContent_lbRD" style="width:188px;">
<option value="5">one</option>
<option value="1">two</option>
</select>
<input id="btnAdd" type="button" value="Добавить" onclick="JSAdd();" />
<input id="btnEdit" type="button" value="Редактировать" onclick="JSEdit();" />
</div>
<div id="ctl00_MainContent_divDetail" style="display:none" clientidmode="static">
<div id="ctl00_MainContent_upnlDescription">
<div>
<span id="ctl00_MainContent_lblDescription">Описание:</span>
<input name="ctl00$MainContent$txtDescription" type="text" id="ctl00_MainContent_txtDescription" />
<span id="ctl00_MainContent_txtDescriptionRequiredFieldValidator" style="color:Red;visibility:hidden;">Описание является обязательным для заполнения</span>
</div>
<input type="submit" name="ctl00$MainContent$btnSave" value="Сохранить" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$btnSave", "", true, "", "", false, false))" id="ctl00_MainContent_btnSave" />
I need to be able to make the div invisible again from code-behind. I cannot access the div unless it is runat="server". But when I add runat="server", the div doesn't become visible on pressing the button from the javascript function above. Could you please help me with this?
Thanks,
David
You can access a div in code-behind by adding the runat="server" attribute. Adding this attribute does change the way you access the element in JavaScript though:
var el = document.getElementById("<%=div1.ClientID%>");
if (el){
el.style.display = "none"; //hidden
}
There are two ways to adjust the visibility from code-behind, but since you're setting display:none in JavaScript, you'd probably want to use the same approach in code-behind:
div1.Style["display"] = "block"; //visible
In code-behind, you can also set the Visible property to false, but this is different because it will prevent the element from being rendered at all.
EDIT
If the div is still showing with display:none present, you probably have an unclosed tag or quote somewhere affecting the markup. Double check and make sure that the markup is valid.
Use a Panel, it renders as a classic div
<asp:Panel runat="server" ID="divDetail" ClientIDMode="Static" />
You have a few options, use ClientIDMode="Static" or use the dynamic ClientID at run-time. Both of these options give you server-side access to the object.
Dynamic:
<div id="divDetail" runat="server" />
//or
<asp:panel id="divDetail" runat="server" />
function JSAdd() {
document.getElementById('<%= divDetail.ClientID %>').style.display = "block";
}
//to hide from code-beind
divDetail.Attributes.Add("style","display:none;");
Static(.NET 4.0 +):
<div id="divDetail" runat="server" ClientIdMode="Static">
//or
<asp:panel id="divDetail" runat="server" ClientIdMode="Static" />
function JSAdd() {
document.getElementById('divDetail').style.display = "block";
}
When runat="server" is applied to an element, asp.net ensures that it has a unique ID by mangling it. Simply ask asp.net for the real client id:
function JSAdd() {
document.getElementById("<%=div1.ClientID%>").style.display = "block";
}
Alternatively, you could tell asp.net to leave your ID alone by adding this to your div:
<div id="div1" runat="server" clientidmode="Static">
Resources:
ClientIdMode="Static" docs
In ASP.NET, to make IDs unique (if multiple control loaded where same ID are specified), ID on elements are often follow a convention like ctl00_container1_container2_controlID and this is what returned when you call control.ClientID.
If you consider such a case where there's same ID on the serverside and you loaded those two controls in your page, you may consider using jQuery and life would be easier with runat="server" with just matching the ID with the end part:
function JSAdd() {
$("div[id$=divDetails]").show();
}
Simplest technique will be to use Javascript/Jquery to Changes Display property of the Div. if not that you can use following code
<form method="post" runat="server">
<div style = "display:none" id= "div1" runat ="server" >Hello I am visible</div>
<asp:Button Text="display Div" runat ="server" ID ="btnDisplay" OnClick = "displayDiv" />
<asp:Button Text="display Div" runat ="server" ID ="btnHideDiv" OnClick = "hideDiv" />
</form>
code behind code is as follows
protected void displayDiv(object sender, EventArgs e)
{
div1.Style.Clear();
div1.Style.Add("display", "block");
}
protected void hideDiv(object sender, EventArgs e)
{
div1.Style.Clear();
div1.Style.Add("display", "none");
}
guess you Got your solution