Why is linkbutton OnClick not firing? - asp.net

This is driving me crackers, it's very basic code, just a very basic three textbox contact form and a linkbutton.
<div class="form-group has-feedback">
<asp:Label ID="lblYourName" AssociatedControlID="txtYourName" CssClass="col-sm-3 control-label" runat="server" Text="Your name"></asp:Label>
<div class="col-sm-6">
<asp:TextBox ID="txtYourName" TextMode="SingleLine" CssClass="form-control" runat="server" placeholder="Your name"></asp:TextBox>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
<asp:Label ID="lblNoName" runat="server" Visible="false" Text="Please enter your name"></asp:Label>
</div>
</div>
<div class="form-group has-feedback">
<asp:Label ID="lblEmail" runat="server" AssociatedControlID="txtEmail" Text="Email" CssClass="col-sm-3 control-label"></asp:Label>
<div class="col-sm-6">
<asp:TextBox ID="txtEmail" CssClass="form-control" runat="server" placeholder="Email" TextMode="Email"></asp:TextBox>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
<asp:Label ID="lblNoEmail" runat="server" Visible="false" Text="Please enter your email"></asp:Label>
</div>
</div>
<div class="form-group">
<asp:Label ID="lblMessage" AssociatedControlID="txtMessage" CssClass="col-sm-3 control-label" runat="server" Text="Your message"></asp:Label>
<div class="col-sm-6">
<asp:TextBox ID="txtMessage" CssClass="form-control" TextMode="MultiLine" placeholder="Your message" runat="server"></asp:TextBox>
</div>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-6">
<asp:LinkButton ID="lnkSubmit" runat="server" OnClick="lnkSubmit_Click" CssClass="btn standard-hover-effect bg-red btn-lg btn-block">
<span class="text">Contact us <i class="fa fa-arrow-right"></i></span>
</asp:LinkButton>
</div>
</div>
The OnClick of the linkbutton points to this simple MailMessage method where it checks name and email boxes are filled in and then sends an email.
protected void lnkSubmit_Click(object sender, EventArgs e)
{
lblNoName.Visible = false;
lblNoEmail.Visible = false;
if (string.IsNullOrEmpty(txtYourName.Text) || string.IsNullOrEmpty(txtEmail.Text))
{
if (!string.IsNullOrEmpty(txtYourName.Text))
{
lblNoName.Visible = false;
}
else
{
lblNoName.Visible = true;
}
if (!string.IsNullOrEmpty(txtEmail.Text))
{
lblNoEmail.Visible = false;
}
else
{
lblNoEmail.Visible = true;
}
}
else
{
MailMessage mm = new MailMessage(txtEmail.Text, "foo#bar.com");
mm.Subject = "Feedback from website";
mm.Body = "Email from " + txtYourName.Text + "<br /><br />" + txtMessage.Text;
SmtpClient smtp = new SmtpClient();
smtp.Host = "mail.websitelive.net";
smtp.Send(mm);
panContactThanks.Visible = true;
}
}
But when I click the submit button, nothing happens. At all. The OnClick doesn't even fire so the breakpoint in the code behind doesn't even get called. It's as if the OnClick even isn't even in the code and it's just a dummy button. What have I missed out?

Please try CauseValidation="false" in link button.
Like:
<asp:LinkButton ID="lnkSubmit" runat="server" OnClick="lnkSubmit_Click"
CauseValidation="false" CssClass="btn standard-hover-effect bg-red btn-lg btn-block">

Wrap your html inside form tag
<form id="someForm" runat="server">
<!--your html-->
</form>
You are using .net server controls, so you need to wrap them inside form. Don't forget to add runat="server"
http://forums.asp.net/t/1463877.aspx?Does+an+aspx+must+have+a+form+tag+

Probably you forgot to add the isPostBack condition in your Page_load
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Control initialization here
}
}
Take a look at ASP.NET page life cycle: https://msdn.microsoft.com/en-us/library/ms178472.aspx
IsPostBack: https://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback(v=vs.110).aspx

Related

Coudn't pass the form values one page to another asp.net

i have to values values one form to another using asp.net i can pass to another only regno and name only another values cannot pass i got the error missing directive what i tried so far i attached below
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label>Reg No</label>
<asp:TextBox ID="regno" runat="server" class="form-control" required></asp:TextBox>
</div>
<div class="form-group">
<label>Name</label>
<asp:TextBox ID="name" runat="server" class="form-control" required></asp:TextBox>
</div>
<div class="form-group">
<label>Address</label>
<input type="text" id="phone" name="phone" class="form-control" required />
</div>
<div class="form-group">
<label>Gender</label>
<asp:RadioButton ID="RadioButton1" runat="server" OnCheckedChanged="RadioButton1_CheckedChanged" Text="Male" />
<asp:RadioButton ID="RadioButton2" runat="server" Text="FeMale" />
</div>
<div class="form-group">
<label>Interest</label>
<asp:CheckBox ID="CheckBox1" runat="server" Text="Cricket" />
<asp:CheckBox ID="CheckBox2" runat="server" Text="Football" />
<asp:CheckBox ID="CheckBox3" runat="server" Text="Cinima" />
</div>
<div class="form-group">
<asp:Button ID="Button1" runat="server" Text="Submit" class="btn btn-success" OnClick="Button1_Click" />
</div>
</div>
Button Event
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("form2.aspx?regno=" +
this.regno.Text + "&name=" +
this.name.Text + "&phone=" +
this.phone.Text ); this line i got error missing directive
}
Second form
Label1.Text = Request.QueryString["regno"];
Label2.Text = Request.QueryString["name"];
Label3.Text = Request.QueryString["phone"];
phone seems to be ordinary input and not TextBox (note the input tag and lowercase id). Also, you are requesting a txtphone while id=phone.
Be aware, string data should be Url encoded before sending it through querystring.
Edit: replace
<input type="text" id="phone" name="phone" class="form-control" required />
with
<asp:TextBox ID="phone" runat="server" class="form-control" required></asp:TextBox>
Edit: for checkboxes, use something like
var interests = new List<string>();
if (chkCheckBox1.Checked)
interests.Add(chkCheckBox1.Text);
if (chkCheckBox2.Checked)
interests.Add(chkCheckBox2.Text);
if (chkCheckBox3.Checked)
interests.Add(chkCheckBox3.Text);
var interestsString = string.Join(",", interests);
var sex = RadioButton1.Checked ? RadioButton1.Text : RadioButton1.Text;
Response.Redirect("form2.aspx" +
"?regno=" + this.regno.Text +
"&name=" + this.name.Text +
"&phone=" + this.phone.Text +
"&sex=" + HttpUtility.UrlEncode(sex) +
"&interest=" + HttpUtility.UrlEncode(interestsString) +
// if needed, decode with HttpUtility.UrlDecode(Request.QueryString["interest"]:
// var interests = HttpUtility.UrlEncode(interestsString);

How to access the id of a TextBox in the repeater code behind

I have a repeater below;
<asp:Repeater ID="RptRE" runat="server">
<ItemTemplate>
<div id="headingCollapse2" runat="server">
<a data-toggle="collapse" href="#link<%#Eval("IDmessage")%>" aria-expanded="false" aria-controls="link<%#Eval("IDmessage")%>">
<asp:TextBox ID="getid" runat="server"></asp:TextBox>
<div class="media">
<span class="avata">
<img class="media" src="../pics/<%#Eval("Picsender")%>"></span>
</div>
<div class="media">
<h6 class="list"><%#Eval("SubjectMessage")%></h6>
<p class="ltext">
<span><%#Eval("DateSendMessage")%></span>
</p>
</div>
</a>
</div>
<div id="link<%#Eval("IDmessage")%>" role="tabpanel" aria-labelledby="headingCollapse2" class="card-collapse collapse" aria-expanded="false" style="">
<p><%#Eval("ContentMessage")%></p>
</div>
</ItemTemplate>
</asp:Repeater>
In line 5 I have a textbox
<asp:TextBox ID="getid" runat="server"></asp:TextBox>
I can't get the ID of the TextBox code-behind. Is there any specific reason? Does anybody know how to get it?
Thanks
I've made a simple demo with 2 examples of how to get the data out of the Repeater. One example is per row and the other all rows at once. Just make sure you bind data in an IsPostBack check.
<asp:Repeater ID="RptRE" runat="server" OnItemCommand="RptRE_ItemCommand">
<ItemTemplate>
<asp:TextBox ID="getid" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="This Item" CommandName="Show" />
<hr />
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="Button1" runat="server" Text="All Items" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
Code behind
protected void RptRE_ItemCommand(object source, RepeaterCommandEventArgs e)
{
//get the correct textbox from the ItemIndex
var textbox = (TextBox)RptRE.Items[e.Item.ItemIndex].FindControl("getid");
//show result
Label1.Text = textbox.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in RptRE.Items)
{
var textbox = (TextBox)item.FindControl("getid");
Label1.Text += textbox.Text + "<br>";
}
}

Bootstrap modal losing data when displayed

I have a form that has various buttons on that when clicked display a modal popup. The popup displays correctly on the screen, but no data appears in any of the fields.
When I step through the code I can see that the data is being assigned to the relevant controls (textbox or label) but nothing appears. In my project I have several other forms that also have popups and these work as they should. I have even used the code from these forms to try and solve the issue but with no success.
This is the code where the user clicks the button to display the popup
<div class="tab-pane fade" id="tabDiary">
<div class="col-md-12">
<asp:UpdatePanel ID="updatePanelDiary" runat="server">
<ContentTemplate>
<%--<asp:Timer ID="timerDiary" runat="server" Interval="15000" OnTick="timerDiary_Tick"></asp:Timer>--%>
<asp:Repeater ID="rptDiary" runat="server" OnItemDataBound="rptDiary_ItemDataBound">
<HeaderTemplate>
<div class="col-md-12 text-right">
<div class="form-group">
<asp:Button ID="btnDiary" runat="server" Text="New Diary Item" OnClick="btnDiary_Click" CssClass="btn btn-warning" Visible="true" />
<div class="clearfix"></div>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr class="tabHeaderRow">
<td>Date</td>
<td>Entered By</td>
<td>Comments</td>
<td>Action Date</td>
<td></td>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem,"DateEntered") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"AddedBy") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"Comments") %></td>
<td><asp:Label ID="lblActionDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"ActionDate") %>'></asp:Label></td>
<td><asp:Button ID="btnEditDiaryEntry" runat="server" CssClass="btn btn-primary btn-sm" Text="Edit" CommandName="EditDiaryEntry"
OnCommand="btnEditDiaryEntry_Command" CommandArgument='<%#Eval("DiaryID") %>' /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="clearfix"></div>
</div>
This is the code behind:
protected void btnEditDiaryEntry_Command(object sender, CommandEventArgs e)
{
Int32 DiaryID = Convert.ToInt32(e.CommandArgument);
SqlCommand cmd = new SqlCommand("sp_GetDiaryEntry", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DiaryID", DiaryID);
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtEditComment.Text = dr["Comments"].ToString();
txtEditScheduleDiary.Text = dr["ActionDate"].ToString();
}
dr.Close();
cnn.Close();
ScriptManager.RegisterStartupScript(_parentControl, _parentControl.GetType(), "Modal", " DisplayEditDiaryModal()", true);
Master.GetMenuData();
txtEditScheduleDiary.Text = "hello david";
}
And this is the code to display the popup
<script type="text/javascript">
function DisplayEditDiaryModal() {
$('#<%=pnlDiaryEdit.ClientID%>').modal('show');
}
</script>
This is the code for the modal:
<asp:Panel ID="pnlDiaryEdit" runat="server" class="modal fade" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="well well-md">
<fieldset>
<legend class="text-center header"><asp:Label ID="Label31" Text="Edit Diary Entry" runat="server" Visible="true"></asp:Label></legend>
<asp:HiddenField ID="hidDiaryID" runat="server" />
<div class="form-group">
<div class="col-md-3">
<asp:Label ID="lblEditComment" runat="server" Text="Comment"></asp:Label>
</div>
<div class="col-md-9">
<asp:TextBox ID="txtEditComment" runat="server" CssClass="form-control" TextMode="MultiLine" Rows="10" Wrap="true" ></asp:TextBox>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<div class="col-md-3">
<asp:Label ID="lblEditSchedule" runat="server" Text="Schedule Event"></asp:Label>
</div>
<div class="col-md-6">
<asp:TextBox ID="txtEditScheduleDiary" runat="server" CssClass="form-control" Visible="true" ></asp:TextBox>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<div class="col-md-12 text-right">
<asp:Button ID="btnCancelEdit" runat="server" Text="Cancel" CssClass="btn btn-primary" OnClientClick="HideEditDiaryModal(); return false;" />
<asp:Button ID="btnEditDiary" runat="server" Text="Edit" CssClass="btn btn-success" OnClick="btnEditDiary_Click" />
</div>
</div>
</fieldset>
</div>
</div>
</div>
</div>
</div>
</div>
As I have already said this code works on other forms within the project. Any help would be much appreciated.
Have you tried adding updatePanelDiary.Update()?
protected void btnEditDiaryEntry_Command(object sender, CommandEventArgs e)
{
Int32 DiaryID = Convert.ToInt32(e.CommandArgument);
SqlCommand cmd = new SqlCommand("sp_GetDiaryEntry", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DiaryID", DiaryID);
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtEditComment.Text = dr["Comments"].ToString();
txtEditScheduleDiary.Text = dr["ActionDate"].ToString();
}
dr.Close();
cnn.Close();
ScriptManager.RegisterStartupScript(_parentControl, _parentControl.GetType(), "Modal", " DisplayEditDiaryModal()", true);
Master.GetMenuData();
txtEditScheduleDiary.Text = "hello david";
updatePanelDiary.Update();
}
And add UpdateMode="Conditional" to your update panel
<asp:UpdatePanel ID="updatePanelDiary" runat="server" UpdateMode="Conditional">

friendly URLS Login page postback

Problem
I'm working on the loginscreen of my website. I used my own template but added the "RequiredFieldValidator" for my password and username. When I click the ASP:Button without filling in the textboxes. The RequiredFieldValidator errormessages appears for 1 second but then the page refreshes.
Platforms
Firefox
Chrome
Opera
My thoughts
I think this has to do with the friendly urls nuget. I didn't touch this but when I click the login button and look at the networkevents (in Chrome - F12) I see that it's /Account/Login?.......... so without the '.aspx'
HTML-Code
<form role="form">
<div class="form-group">
<div class="input-group login-input">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<asp:TextBox runat="server" id="LoginUserName" type="text" class="form-control" placeholder="Username"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="LoginUserName"
CssClass="text-danger" Display="Dynamic" ErrorMessage="The user name field is required." />
</div>
<br>
<div class="input-group login-input">
<span class="input-group-addon"><i class="fa fa-lock"></i></span>
<asp:TextBox runat="server" id="LoginPassword" type="password" class="form-control" placeholder="Password"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="LoginPassword"
CssClass="text-danger" Display="Dynamic" ErrorMessage="The password field is required." />
</div>
<div class="checkbox">
<label>
<input runat="server" id="InputRememberMe" type="checkbox">
Remember me
</label>
</div>
<div class="input-group login-input">
<asp:Button runat="server" onclick="LogIn" class="btn btn-primary pull-right" Text="Login" />
<asp:PlaceHolder runat="server" ID="ErrorMessage" Visible="false">
<p class="text-danger">
<asp:Literal runat="server" ID="FailureText" />
</p>
</asp:PlaceHolder>
</div>
<hr>
Create Account
Password Recovery
<div class="clearfix"></div>
</div>
C# Code
protected void Page_Load(object sender, EventArgs e)
{
//RegisterHyperLink.NavigateUrl = "Register";
//OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
//var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
//if (!String.IsNullOrEmpty(returnUrl))
//{
// RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
//}
}
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
// Validate the user password
var manager = new UserManager();
ApplicationUser user = manager.Find(LoginUserName.Text, LoginPassword.Text);
if (user != null)
{
IdentityHelper.SignIn(manager, user, InputRememberMe.Checked);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
FailureText.Text = "Invalid username or password.";
ErrorMessage.Visible = true;
}
}
}
I solved my problem. I had a form tag in my masterpage but also in my login page which gives a warning. This blocked everything...

find hidden field value when link button is inside nested repeater

<asp:Repeater ID="rptHotels" runat="server" OnItemDataBound="rptHotels_ItemDataBound">
<ItemTemplate>
<div class="hotel-box">
<div class="hotel-img">
<asp:HiddenField ID="hdnHotelCode" runat="server" Value='<%#Eval("HotelCode")%>' />
<a class="preview" href='<%#Eval("ImageURL_Text") %>' title='<%#Eval("HotelName")%>' target="_blank">
<img src='<%#Eval("ImageURL_Text") %>' alt='<%#Eval("HotelName")%>' height="75px"
width="100px" />
</a>
</div>
<div class="hotel_heeading_content">
<div class="hotel_heading">
<h2>
<asp:LinkButton ID="lnkHotelDetail" runat="server" OnClick="lnkHotelDetail_Click">
<%#Eval("HotelName")%>
(
<%#Eval("boardType")%>)
</asp:LinkButton>
</h2>
</div>
<div class="stars">
<span class="stars">
<%#Eval("StarRating")%></span>
</div>
<div class="hotel_text">
<%#Eval("HotelAddress")%>,
<%#Eval("Destination")%>
,<%#Eval("Country")%>
<img src="images/ico_point2.png" alt="" id="mapicon" class="mapicon" />
<input type="hidden" id="hdnLatitude" class="hdnLatitude" runat="server" value='<%#Eval("Latitude")%>' />
<input type="hidden" id="hdnLongitude" class="hdnLongitude" runat="server" value='<%#Eval("Longitude")%>' />
<input type="hidden" id="hdnInfoWindow" class="hdnInfoWindow" runat="server" />
</div>
</div>
<p>
<asp:Literal ID="ltDes" runat="server"></asp:Literal>
</p>
<p>
more info
</p>
<div class="btn">
<asp:LinkButton ID="lnkPrice" runat="server" Text=' <%#Eval("totalPrice")%>' OnClick="lnkHotelDetail_Click" ></asp:LinkButton>
</div>
<div class="roominfo">
<asp:Repeater ID="rptRooms" runat="server">
<HeaderTemplate>
<div class="rooms">
<div class="roominfoheader">
<div class="roomheaderlbl">
Room Name</div>
<div class="roomheaderlbl">
Total Room Rate</div>
<div class="roomheaderlbl">
Book Now</div>
</div>
</div>
</HeaderTemplate>
<ItemTemplate>
<div class="rooms">
<div class="roominforow">
<div class="roominforowlbl">
<asp:Label ID="lblRoomName" runat="server" Text='<%#Eval("roomCategory") %>'></asp:Label></div>
<div class="roominforowlbl">
$
<asp:Label ID="Label1" runat="server" Text='<%#Eval("totalRoomRate") %>'></asp:Label></div>
<div class="roominforowlbl">
<asp:LinkButton ID="lnkBookNow" runat="server" Text="Book Now" OnClick="lnkBookNow_Click"></asp:LinkButton></div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I have above HTML for nested repeater .I am able to find the hidden field value which contain hotel Code by following method
protected void lnkHotelDetail_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
var item = (RepeaterItem)btn.NamingContainer;
HiddenField hdnHotelCode = (HiddenField)item.FindControl("hdnHotelCode");
}
but the problem is now i have to find the hidden field value when a nested repeater item template link button is clicked .You can check that lnkBookNow is link button which is inside the rptRooms repeater.
protected void lnkBookNow_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
var item = (RepeaterItem)btn.NamingContainer;
HiddenField hdnHotelCode = (HiddenField)item.FindControl("hdnHotelCode");
}
I tried something like this but its not finding hidden field.
The problem here is that lnkBookNow.NamingContainer is rptRooms. This control obviously does not contain hdnHotelCode.
I think you should be able to do this with:
protected void lnkBookNow_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
var item = (RepeaterItem)btn.NamingContainer.NamingContainer.NamingContainer;
HiddenField hdnHotelCode = item.FindControl("hdnHotelCode") as HiddenField;
}
btn.NamingContainer is a RepeaterItem in rptRooms. The NamingContainer of that is the Repeater itself. Finally, the NamingContainer of rptRooms is the RepeaterItem of rptHotels, in which you want to find your HiddenField.
Note my use of the as keyword instead of an explicit cast - this will protect you from NullReferenceExceptions if FindControl returns null. Of course, you should explicitly check that hdnHotelCode isn't null before you try to access it.

Resources