I am unable to get my button to activate my code behind. I have tried adding asp-source, asp-action, runat, and every time my onclick does not work and I get the error:
47 Uncaught ReferenceError: PlayerHit is not defined
at HTMLUnknownElement.onclick
This is my markup:
<asp:Button runat= "server" id="butAddPlayerCard" onclick="PlayerHit">Hit2</asp:Button>
<button onclick="PlayerHit" id="finalButton" runar>Final</button>
<button ID="Button2" onclick="PlayerHit" runat="server" Class="btn btn-primary btn-light">Hit</button>
I just need one button but this is to show what I have tried.
Code behind:
public void PlayerHit(object sender, EventArgs e)
{
DeckAction deckAction = new DeckAction();
deckAction.AddCard(deck, PlayersHand);
foreach (var item in PlayersHand)
{
if ((item.Values) == 0)
{
var cardValue = item.Values;
}
}
}
This code is in the main class of the file.
According to Button.OnClick method, it should be OnClick but not onclick. And use the Web form control.
<asp:Button ID="Button2" OnClick="PlayerHit" runat="server"
Class="btn btn-primary btn-light">Hit</asp:Button>
Related
I have a button in my gridview and when the users click on it, it goes to the page. However, if you right click on it and "open link in a new tab" it goes to a blank page. I want it so when the user right click on it and "open link in a new tab" to go to the page. This is the code that I have so far:
aspx
<asp:LinkButton ID="lnkEditbtn" data-toggle="tooltip" title="View Request" OnClick="lnkEditbtn_Click" runat="server" class="btn btn-primary btn-sm" Text="<%# bind('ticketID')%>"></asp:LinkButton>
c#
protected void lnkEditbtn_Click(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
Label lblid = (Label)gvr.FindControl("lblMovie");
int id = Convert.ToInt32(lblid.Text.ToString());
SecureQueryString qs = new SecureQueryString();
qs["ID"] = id.ToString();
Response.Redirect("viewMovie.aspx?qs=" + qs.ToString());
}
you cannot do this with linkbutton because it redirects to the desired view after you click on it but you can use asp:HyperLink and set its value like
<asp:HyperLink ID="lnkEditbtn" data-toggle="tooltip" Text="View Request" runat="server" NavigateUrl='<%# Eval("ticketID", "~/viewMovie.aspx?qs={0}") %>' class="btn btn-primary btn-sm" ></asp:HyperLink >
Edit
if you want the URL to be encrypted first create a class
public static class encrypt
{
public static string encvalue(int id)
{
SecureQueryString qs = new SecureQueryString();
qs["ID"] = id.ToString();
return qs.ToString()
}
}
and your hyperlink will be
<asp:HyperLink ID="lnkEditbtn" data-toggle="tooltip" Text="View Request" runat="server" NavigateUrl='<%# String.Format("~/viewMovie.aspx?qs={0}",encrypt.encvalue(Convert.ToInt32(Eval("ticketID")))) %>' class="btn btn-primary btn-sm" ></asp:HyperLink >
Link button in server side gets rendered to Hyperlink in client side with 'href' as href="javascript:__doPostBack('lnkEditbtn',''), which is nothing but a postback to the server from the link button. So when you right click and open the link in a new tab, it posts to the server and hence it comes up as blank page in new tab.
What you can do is use code similar to the below code:
<style>
.hide {
display:none;
}
</style>
<script>
function postBack() {
__doPostBack('lnkEditbtn', '');
return false;
}
</script>
<asp:LinkButton ID="lnkEditbtn" runat="server" OnClick="lnkEditbtn_Click" Text="Link" CssClass="hide"></asp:LinkButton>
Link
protected void lnkEditbtn_Click(object sender, EventArgs e)
{
var linkButton = (Control)sender as LinkButton;
}
With this code, you are hiding the link button and using the Anchor tag instead.
Href in Anchor tag will be invoked when you right click. And when you click the link, "postBack" JS method will be triggered that invokes the server side event handler for the Link Button.
And there by both right click and left click works.
I need to navigate to the certain tab when button is clicked.
The button is
<asp:Button ID="ButtonFind" runat="server" Text="Buscar" CssClass="btn btn-primary" UseSubmitBehavior="true" OnClick="ButtonSearch_Click" />
JavaScript
// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}
// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
window.location.hash = e.target.hash;
})
But somehow the method
protected void ButtonSearch_Click(object sender, EventArgs e)
{
// Fill Grid code
}
is replaced with
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Fill Grid by default
}
}
And finally the grid has no found data and has default data. That's a problem.
I have try to use this
protected void ButtonSearch_Click(object sender, EventArgs e)
{
// Fill Grid code
string url = Request.Url.GetLeftPart(UriPartial.Path) + "#AllWorkOrders";
Response.Redirect(url, true);
}
but there is a
if (!IsPostBack)
{
// Fill Grid by default
}
still ...
I mean I need somehow return user to the correct TAB but Response.Redirect establish some trouble...
Probably there is a way to add #AllWorkOrders part of QueryString to
<asp:Button ID="ButtonFind" runat="server" Text="Buscar" CssClass="btn btn-primary" UseSubmitBehavior="true" OnClick="ButtonSearch_Click" />
but I don't know how to do it.
Any clue?
I found solution that was quite easy to implemenet hahahahaa
I completely forgot about PostBackUrl property!
So the code looks like this now
<asp:Button ID="ButtonFind" runat="server" Text="Buscar" CssClass="btn btn-primary" UseSubmitBehavior="true"
PostBackUrl="~/MyPage.aspx#AllWorkOrders" OnClick="ButtonSearch_Click" />
I am a new developer and I what I am trying to accomplish is hiding the radio buttons in the bottom DIV and the btnSetFinishState when clicked shows the bottom DIV (which it does from code behind). But the radio buttons when clicked do not fire the code behind method.
Here is .aspx:
<div class="row">
<asp:Button ID="btnSetFinishState" runat="server" Text="FINISHED" OnClick="btnSetFinishState_Click" UseSubmitBehavior="False" Enabled="False" />
</div>
<div class="row" id="finishedBlock" runat="server" visible="false">
<asp:Label ID="lblSetFinishText" runat="server" Text="Are you sure you want to set state to finished?" />
<div data-toggle="buttons" id="divRadioButtons">
<label id="btnFinishyes" class="btn btn-default col-sm-6 col-xs-6">
<asp:RadioButton ID="finishyes" Text="Yes" GroupName="finish" runat="server" AutoPostBack="true" OnCheckedChanged="finishyes_CheckedChanged" />
</label>
<label id="btnFinishno" class="btn btn-default col-sm-6 col-xs-6">
<asp:RadioButton ID="finishno" Text="No" GroupName="finish" runat="server" AutoPostBack="true" OnCheckedChanged="finishno_CheckedChanged" />
</label>
</div>
</div>
The aspx.cs code:
protected void btnSetFinishState_Click(object sender, EventArgs e)
{
// if neither radio button clicked
if (!finishyes.Checked && !finishno.Checked)
{
finishedBlock.Visible = true; // show the radio button DIV
//return;
}
}
protected void finishno_CheckedChanged(object sender, EventArgs e)
{
finishedBlock.Visible = false; // hide the radio buttons
finishno.Checked = false; // reset the no button to false
}
protected void finishyes_CheckedChanged(object sender, EventArgs e)
{
// set the finished state code
}
Is there e reason why btnSetFinishState is set to Enabled="False" ?
Because I tested this code and it works
aspx code
<div class="row">
<asp:Button ID="btnSetFinishState" runat="server" Text="FINISHED" OnClick="btnSetFinishState_Click" UseSubmitBehavior="False" Enabled="true" />
</div>
<div class="row" id="finishedBlock" runat="server" visible="false">
<asp:Label ID="lblSetFinishText" runat="server" Text="Are you sure you want to set state to finished?" />
<div data-toggle="buttons" id="divRadioButtons">
<label id="btnFinishyes" class="btn btn-default col-sm-6 col-xs-6">
<asp:RadioButton ID="finishyes" Text="Yes" GroupName="finish" runat="server" AutoPostBack="true" OnCheckedChanged="finishyes_CheckedChanged" />
</label>
<label id="btnFinishno" class="btn btn-default col-sm-6 col-xs-6">
<asp:RadioButton ID="finishno" Text="No" GroupName="finish" runat="server" AutoPostBack="true" OnCheckedChanged="finishno_CheckedChanged" />
</label>
</div>
</div>
aspx.cs
protected void btnSetFinishState_Click(object sender, EventArgs e)
{
// if neither radio button clicked
if (!finishyes.Checked && !finishno.Checked)
{
finishedBlock.Visible = true; // show the radio button DIV
//return;
}
}
protected void finishno_CheckedChanged(object sender, EventArgs e)
{
finishedBlock.Visible = false; // hide the radio buttons
finishno.Checked = false; // reset the no button to false
}
protected void finishyes_CheckedChanged(object sender, EventArgs e)
{
// set the finished state code
Response.Redirect("WebForm2.aspx");
}
I ran your code in my machine and found event's are firing exactly.
So , I think the different between your environment and mine may be <%# Page directive and missing AutoEventWireup="true" property.
Please share your Asp.net version and project info such as
is there any master pages or not.
UPDATE:
Please create a new sample web form application in visual studio and add a new web form say 'form1', paste your aspx and code behind to the newly added 'form1'. Test and if successfull then check the difference in aspx and code behind with your existing project.Also please let us know.
It seems I am struggling with the order of the page life cycle. Based on the user selecting button 1 or 2, I need to have respective controls added dynamically during the Page_Load event. My problem is when a button is clicked the Page_Load event is executed before Button_Click event code is read. There for my variable "doWhat" is not assigned a value until after the Page_Load event. How can I have the "doWhat" variable assigned a value to be read during the Page_Load?
Below is asp.net form code for the two buttons:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" onclick="Button_Click" />
<asp:Button ID="Button2" runat="server" Text="Button 2" onclick="Button_Click" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
Below is the code behind:
int doWhat;
protected void Page_Load(object sender, EventArgs e)
{
doWhat = Convert.ToUInt16(ViewState["doWhat"]);
if (doWhat == 1)
{
// code to dynamically load group 1 controls
}
else
{
// code to dynamically load group 2 controls
}
Label1.Text = Convert.ToString(doWhat);
}
protected void Button_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.ID == "Button1")
{
doWhat = 1;
}
else
{
doWhat = 2;
}
ViewState.Add("doWhat", doWhat);
}
If you are comfortable with javascript then you can achieve it by making following changes in your design and code. Add a hidden field in your aspx page. Your HTML code should be like this.
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button_Click" OnClientClick="return doWhatAction(1);" />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClick="Button_Click" OnClientClick="return doWhatAction(2);" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:HiddenField ID="HiddenField1" Value="1" runat="server" />
<script type="text/javascript">
var doWhatAction = function (actionIndex) {
//alert(actionIndex);
document.getElementById("<%=HiddenField1.ClientID%>").value = actionIndex;
return true;
}
</script>
</div>
</form>
And your code will be something like...
int doWhat;
protected void Page_Load(object sender, EventArgs e)
{
//doWhat = Convert.ToUInt16(ViewState["doWhat"]);
doWhat = Convert.ToUInt16(HiddenField1.Value);
if (doWhat == 1)
{
// code to dynamically load group 1 controls
}
else
{
// code to dynamically load group 2 controls
}
Label1.Text = Convert.ToString(doWhat);
}
protected void Button_Click(object sender, EventArgs e)
{
//Do Nothing
//Button btn = sender as Button;
//if (btn.ID == "Button1")
//{
// doWhat = 1;
//}
//else
//{
// doWhat = 2;
//}
//ViewState.Add("doWhat", doWhat);
}
You can use jquery or javascript i this case.
Took on hidden variable in form
initialize it on click event of button in javascript
Read value of hidden variable in page load
<head >
<title>Hidden Variable</title>
<script type="text/javascript">
function SetHDNValue()
{
var hdnControlID = '<%= hdnControl.ClientID %>';
document.getElementById(hdnControlID).value=1;
}
</script>
</head>
<body >
<form id="form1" runat="server">
<div>
<input id="hdnControl" type="hidden" runat="server" />
<asp:Button ID="btnJSValue" Text="Click" runat="server" OnClientClick="SetHDNValue()"
/>
</div>
</form>
</body>
And in code behind file hdnControl.value
Since long ago I am not working with asp.net forms. And forgot doing things.But I found how you can do. As on stackoverflow link like answers is wrong. I copied main statements from the link which indicate how post-back events works and how you can use it for your purpose. For more http://aspsnippets.com/Articles/How-to-find-the-control-that-caused-PostBack-in-ASP.Net.aspx
All controls accept Button and ImageButton use JavaScript for causing a postback. To enable postback on these controls one has to set AutoPostBack property to true.
When you set this property to true, __doPostBack function is called on event which causes a postback.
The __doPostBack function is not visible in Source of the page until you place a LinkButton or set AutoPostBack to true for any of the above discussed controls.
Here is how generated __doPostBack looks:
<script type = "text/javascript">
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
</script>
The __doPostBack function simply stores the below two arguments in two hidden fields
eventTarget – The name of the control that caused the postback
eventArgument – The argument to be sent to server.
In two hidden fields which also appear only when AutoPostBack is set to true
Finally, here is how you can distinguish by getting control's ID that caused the postback :
if (IsPostBack)
{
string CtrlID = string.Empty;
if (Request.Form["__EVENTTARGET"] != null &&
Request.Form["__EVENTTARGET"] != string.Empty)
{
CtrlID = Request.Form["__EVENTTARGET"];
/****implement Your logic depending on control ID****/
}
}
Here i am trying to do a email validation for a textbox using jquery and am calling that function on onclientclick and i have a button click event too.But the button click event is firing before the javascript function.I need to validate the textbox before firing the button click event.Here is my code
$(document).ready(function () {
$("#MainContent_txtEmail").blur(function () {
ValidateEmail();
});
function ValidateEmail()
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddress = $("#MainContent_txtEmail").val();
if (!emailReg.test(emailaddress)) {
$("#emailspan").html('<font color="red" size=2px;>Please enter valid Email address</font>');
return false;
}
else {
$("#emailspan").html('<font color="red"></font>');
return true;
}
}
});
and
<asp:TextBox ID="txtEmail" name="txtEmail" runat="server" CausesValidation="false" TextMode="Email">
</asp:TextBox><span id="emailspan" value="0"></span>
<asp:Button ID="btnsubmit" CssClass="btn pdf-submit" runat="server" Text="SEND" OnClientClick="return ValidateEmail();" OnClick="btnsubmit_Click"/>
and my event
protected void btnsubmit_Click(object sender, EventArgs e)
{
SendSmtpEmail(txtEmail.Text, "noreply#a.net", "test", "test-template");
}
Any suggestion??
hey In your code ::
`$("#MainContent_txtEmail").blur(function ()
why you are calling the function you may have to change that in to
$("#txtEmail").blur(function ()`
this will work I guess !!
You'll want to remove the OnClick for btnsubmit
<asp:Button ID="btnsubmit" CssClass="btn pdf-submit" runat="server" Text="SEND" OnClientClick="return ValidateEmailThenSubmit();" />
Then click the btnsubmit manually in code after the validation.
function ValidateEmailThenSubmit()
{
ValidateEmail();
$("#" + <%= btnsubmit.ClientID %>).click();
}
Why use javascript? Just use the asp.net RegularExpressionValidator like so:
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
More info here http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator.aspx
The ValidateEmail() method is not visible being declared inside the anonymous method passed as argument to the $.ready() method.
Get the ValidateEmail method outside $(document).ready and it should work.