LinkButton click event not firing asp.net - javascript

I dont know why linkbutton onclick event is not firing. I have tried rewriting the code. I have tried to redirect directly on button click function. I have tried setting a break point inside dashbut_Click() on redirectUser() line but it never reaches there. Kindly help me figure this out.
HTML:
<li><asp:LinkButton ID="dashbut" runat="server"
CausesValidation="false"
OnClick="dashbut_Click"
Text="Dashboard">
<img src="images/dash.png" height="25" width="25" class="fa fa-tachometer" /><span> Dashboard</span>
</asp:LinkButton>
</li>
Code Behind:
protected void dashbut_Click(object sender, EventArgs e)
{
//Response.Redirect("~/Views/Portal/AdminDashboard.aspx");
redirectUser();
}
private void redirectUser()
{
string myConnection = dbController.connectionString;
SqlConnection conn = new SqlConnection(myConnection);
string userCheckQuery = "SELECT UserType from tblUsers where ID = '" + USERid + "'";
SqlCommand cmd1 = new SqlCommand(userCheckQuery, conn);
conn.Open();
bool userType = (bool)cmd1.ExecuteScalar();
conn.Close();
if (userType == true)
{
Response.Redirect("~/Views/Portal/AdminDashboard.aspx");
}
else if (userType == false)
{
Response.Redirect("~/Views/Portal/Dashboard.aspx");
}
}
EDIT:
It seems that the LinkButton click event is not firing because of a JS Error. I dont know how that is related but when I click on the button and view the error on browser Inspect Element I see the following TypeError.
Uncaught TypeError: theForm.submit is not a function
at __doPostBack (NewArtist.aspx:63)
at <anonymous>:1:1
This is the script:
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
Error is on theForm.submit(); line.
This is beyond me. Help me out.

So the problem seemed to be with JavaScript. Actually there was a button on my page with ID=submit this was overriding submit() function on the form, hence the error. This helped
Thumbs Up for Stackoverflow Community.

Sorry if I can't comment due to low reputation points. I would like to know if you need CauseValidation set to false.
Try adding usesubmitbehavior="false".

Related

Adding Hyperlinks to ValidationSummary using programatically added validators

I'm using the javascript from the answer in this question in a project of mine:
Adding Hyperlinks to ValidationSummary
It works really great. I've added it to the bottom of my masterpage (for some reason, even though it is inside $(document).ready, Page_Validators is null if i place it in the head section)
Anyway! I'm also adding some custom validators programatically on postback using this code:
public static CustomValidator ReturnErrorMessage(string message, string validationGroup, string controlToValidate = "")
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ErrorMessage = message;
control.ControlToValidate = controlToValidate;
return control;
}
However whenever I add a CustomValidator like that, in a button event, page_load or whatever, Page_Validators will be overridden and the errormessage will revert to the message without a anchor.
What gives? Am I doing something wrong or can someone explain what is happening?
I've tried debugging it and it does set the values correctly, but then it just reset afterwards.
I've tried for the heck of it and in $(document).ready set all validators as isvalid = false, and that gets overwritten too.
Im using asp.net 4.5 unobtrusive validation, but it does not make a difference if I turn it off.
Adding the javascript in code using Page.ClientScript.RegisterStartupScript at some point after the validator has been created does not work either.
If I don't add any validators in code everything works as expected.
I'm aware I can just add the anchor tags manually, but this is a lot of work to update existing validators instead of just tossing in a small script, so I'm hoping to get this to work.
You can use this code to test this:
using System;
using System.Web.UI.WebControls;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + txtName.ClientID;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = "errorGroup";
control.ErrorMessage = "Error message";
control.ControlToValidate = txtName.ClientID;
Form.Controls.Add(control);
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:ValidationSummary ID="vsSummary" runat="server" ValidationGroup="errorGroup" ForeColor="Red" HeaderText="Error!" />
</div>
</form>
<script>
$(document).ready(function() {
var validators = Page_Validators; // returns collection of validators on page
$(validators).each(function() {
//get target control and current error validation message from each validator
//[0] is needed when using aspnet 4.5 unobtrusive validation
var validator = $(this)[0];
var errorMsg = validator.errormessage;
var targetControl = validator.controltovalidate;
//make link only if theres a control to target
if (targetControl) {
var errorMsgWithLink = "<a href='#" + targetControl + "' style='color: #FF3232;'> " + errorMsg + "</a>";
//update error message with anchor tag
validator.errormessage = errorMsgWithLink;
}
});
});
</script>
</body>
</html>
If you want you can try implementing your own 'CustomValidationSummary' control by following the same design pattern as mentioned at Reference Source by Microsoft, and modify the render method to include anchor tag to wrap error text, before it is passed into the writer method at line number 462.
I ended up using a extension method, adding the anchor tag in the method
public static void AddValidator(this Page p, string message, string validationGroup, string controlToValidate = "", bool addAnchorTags = true)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ControlToValidate = controlToValidate;
if (addAnchorTags && !string.IsNullOrEmpty(controlToValidate))
{
control.ErrorMessage = "<a href='#" + controlToValidate + "' style='color: #FF3232;'> " + message + "</a>";
}
else
{
control.ErrorMessage = message;
}
p.Validators.Add(control);
}

Troubles to open ajaxToolkit:ModalPopupExtender with JavaScript

I'm trying to open a ajaxToolkit:ModalPopupExtender with JavaScript but when I run my code and I call the function from the code behind this crash and show this error.
JavaScript runtime error: Unable to get property 'show' of undefined
or null reference
this is my JavaScript:
<script>
function closeChangeArea() {
$find('ModalChangeArea').hide();
}
function showChangeArea() {
$find('ModalChangeArea').show();
}
</script>
and this is my code:
protected void Btn_Click_Ch_Area(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gr = (GridViewRow)lb.NamingContainer;
Label ToolChange = (Label)gr.FindControl("Lbl_toolg");
Txt_Tool_Reasign.Text = ToolChange.Text;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showChangeArea();", true);
}
this is my ModalPoupExtender
<ajaxToolkit:ModalPopupExtender
ID="ModalChangeArea"
runat="server"
TargetControlID="hid"
PopupControlID="ChangeArea"
RepositionMode="RepositionOnWindowResizeAndScroll"
DropShadow="true"
PopupDragHandleControlID="moveArea">
</ajaxToolkit:ModalPopupExtender>
In asp.net control id is dynamically appended with container, in that case you will not get the control using $find to get control use clientid of asp.net control or set ClientIdMode = "Static".
Try below code to access element.
$find('<%= ModalChangeArea.ClientID %>').show();
$find('<%= ModalChangeArea.ClientID %>').hide();

calling a JavaScript function on Asp.net textBox

Please help! i have been trying to call this function on my Asp.net textbox to format users input while typing.
function format(number) {
var decimalSeparator = ".";
var thousandSeparator = ",";
var result = String(number);
var parts = result.split(decimalSeparator);
if (!parts[1]) {
parts[1] = "00";
}
result = parts[0].split("").reverse().join("");
result = result.replace(/(\d{3}(?!$))/g, "$1" + thousandSeparator);
parts[0] = result.split("").reverse().join("");
return parts.join(decimalSeparator);
}
// i tried using onkeyup, it didnt work
<asp:TextBox ID="txtTransport" runat="server" CssClass="TextBoxes" onKeyup="javaScript: format(this);"></asp:TextBox>
// also i tried using onChange, it didnt work.
<asp:TextBox ID="txtTransport" runat="server" CssClass="TextBoxes" onChange="javaScript:format(this);"></asp:TextBox>
protected void Page_Load(object sender, EventArgs e)
{
txtTransport.Attributes.Add("onKeyup", "javaScript: format(this);");
}
You can do it directly from javascript, not in codebehind !
var el = document.getElementById("<%= txtTransport.ClientID %>");
el.onkeyup = function(e) {
// Do stuff
};
But I think your function is logicaly wrong. Try it anyway. Your ID of a server side control is not exactly the same you write in the code, for get the real ID you can use <%= txtTransport.ClientID %>.

Bootstrap JavaScript breaks ASP.NET postback

Seems like registering bootstrap.js to my page prevents all of my server controls, e.g. asp:LinkButtons and asp:Buttons, from triggering a postback.
I have the following C# script in my masterpage. It just registers jQuery 1.11.1 and Bootstrap.js if the user isn't in Design mode in Kentico. Otherwise it just loads jQuery 1.7.1.
If I don't include bootstrap.js, postbacks from my asp:LinkButtons and asp:Buttons occur as normal. Otherwise, there's just no action happening at all. Any ideas what could be happening?
I don't see any console errors in the browser, and I'm absolutely certain that including Bootstrap.js is somehow partially responsible for this behavior, if not entirely. Everything works just find if it's not included (well, besides bootstrap jQuery modules of course).
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
// Check for null document
if(CMSContext.CurrentDocument != null)
{
if(CMS.PortalEngine.PortalContext.ViewMode.ToString() == "Design")
{
CMS.GlobalHelper.ScriptHelper.RegisterJQuery(this.Page);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"jquery","<script src=\"//code.jquery.com/jquery-1.11.2.min.js\"><" + "/script>",false);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"bootstrap","<script src=\"/getmedia/453e9ad5-e05c-4fb2-b134-4d9cbd00c917/bootstrap-min.aspx\"><" + "/script>",false);
}
}
}
</script>
That bootstrap.min.js file is just the default bootstrap.min.js file for v3.3.2
CODE IN-FRONT
<%# Control Language="C#" AutoEventWireup="true" CodeFile="IssuesSettings.ascx.cs" Inherits="CustomCode_Dashboard_Issues_Issues" %>
<div class="col-xs-12">
<div class="gap"></div>
<div class="btn-group" data-toggle="buttons">
<asp:LinkButton runat="server" ID="ButtonCompletedProjects" CssClass="btn btn-default btn-xs" OnClick="ButtonCompletedProjectsClicked">Show Completed Projects</asp:LinkButton>
<asp:LinkButton runat="server" ID="ButtonClosedIssues" CssClass="btn btn-default btn-xs" OnClick="ButtonClosedIssuesClicked">Show Closed Issues</asp:LinkButton>
</div>
</div>
CODE BEHIND
public partial class CustomCode_Dashboard_Issues_Issues : System.Web.UI.UserControl
{
// cookie name constants
private const string CookieClosedIssuesName = "Dashboard-Issues-ShowClosedIssues";
private const string CookieCompletedProjectsName = "Dashboard-Issues-ShowCompletedProjects";
// boolean switches
private bool _showClosedIssues;
private bool _showCompletedProjects;
protected void Page_Load(object sender, EventArgs e)
{
SetShowClosedIssues();
SetShowCompletedProjects();
SetButtonStyles();
}
private void SetButtonStyles()
{
if (_showClosedIssues)
{
ButtonClosedIssues.CssClass += " active";
}
else
{
ButtonClosedIssues.CssClass += " inactive";
}
if (_showCompletedProjects)
{
ButtonCompletedProjects.CssClass += " active";
}
else
{
ButtonCompletedProjects.CssClass += " inactive";
}
}
private void SetShowCompletedProjects()
{
if (Request.Cookies[CookieCompletedProjectsName] != null)
{
_showCompletedProjects = Convert.ToBoolean(Request.Cookies[CookieCompletedProjectsName].Value);
}
else
{
_showCompletedProjects = false;
}
}
private void SetShowClosedIssues()
{
if (Request.Cookies[CookieClosedIssuesName] != null)
{
_showClosedIssues = Convert.ToBoolean(Request.Cookies[CookieClosedIssuesName].Value);
}
else
{
_showClosedIssues = false;
}
}
protected void CLICKER(object sender, EventArgs e)
{
Response.Write("stuff");
}
protected void ButtonClosedIssuesClicked(Object sender, EventArgs e)
{
Response.Write("TEST");
// if we're turning this off
if (_showClosedIssues)
{
HttpCookie cookie = Request.Cookies[CookieClosedIssuesName];
cookie.Name = CookieClosedIssuesName;
cookie.Domain = ".domain.com";
cookie.Value = "False";
Response.Cookies.Set(cookie);
}
// if we're turning this on
else
{
HttpCookie cookie;
if (Request.Cookies[CookieClosedIssuesName] != null)
{
cookie = Request.Cookies[CookieClosedIssuesName];
cookie.Name = CookieClosedIssuesName;
cookie.Domain = ".domain.com";
cookie.Expires = DateTime.MaxValue;
cookie.Value = "True";
Response.Cookies.Set(cookie);
}
else
{
cookie = new HttpCookie(CookieClosedIssuesName);
cookie.Name = CookieClosedIssuesName;
cookie.Domain = ".domain.com";
cookie.Expires = DateTime.MaxValue;
cookie.Value = "True";
Response.Cookies.Set(cookie);
}
}
Response.Redirect(CMSContext.CurrentDocument.AbsoluteURL);
}
protected void ButtonCompletedProjectsClicked(Object sender, EventArgs e)
{
// if we're turning this off
if (_showCompletedProjects)
{
HttpCookie cookie = Request.Cookies[CookieCompletedProjectsName];
cookie.Name = CookieCompletedProjectsName;
cookie.Domain = ".domain.com";
cookie.Value = "False";
Response.Cookies.Set(cookie);
// change style of button
ButtonCompletedProjects.CssClass.Replace("active","inactive");
}
// if we're turning this on
else
{
HttpCookie cookie;
if (Request.Cookies[CookieCompletedProjectsName] != null)
{
cookie = Request.Cookies[CookieCompletedProjectsName];
cookie.Name = CookieCompletedProjectsName;
cookie.Domain = ".domain.com";
cookie.Expires = DateTime.MaxValue;
cookie.Value = "True";
Response.Cookies.Set(cookie);
ButtonCompletedProjects.CssClass.Replace("inactive", "active");
}
else
{
cookie = new HttpCookie(CookieCompletedProjectsName);
cookie.Name = CookieCompletedProjectsName;
cookie.Domain = ".domain.com";
cookie.Expires = DateTime.MaxValue;
cookie.Value = "True";
Response.Cookies.Set(cookie);
}
}
Response.Redirect(CMSContext.CurrentDocument.AbsoluteURL);
}
}
The problem is that the button.js plugin calls preventDefault() on an element with the data-toggle="buttons" data attribute, and the <asp:LinkButton> server control places its '_doPostBack' function call within the href="" attribute of the anchor tag it renders. Therefore the button.js plugin prevents the postback from happening.
I just copy/pasted the markup from the bootstrap docs so I happened to have that attribute on my <div class="btn-group">:
<div class="btn-group" data-toggle="buttons">
<asp:LinkButton runat="server" ID="ButtonCompletedProjects" CssClass="btn btn-default btn-xs" OnClick="ButtonCompletedProjectsClicked">Show Completed Projects</asp:LinkButton>
<asp:LinkButton runat="server" ID="ButtonClosedIssues" CssClass="btn btn-default btn-xs" OnClick="ButtonClosedIssuesClicked">Show Closed Issues</asp:LinkButton>
</div>
The server controls render the following markup:
<div class="btn-group" data-toggle="buttons">
<a id="p_lt_ctl01_pageplaceholder_p_lt_ctl02_IssuesSettings_userControlElem_ButtonCompletedProjects" class="btn btn-default btn-xs" href="javascript:__doPostBack('p$lt$ctl01$pageplaceholder$p$lt$ctl02$IssuesSettings$userControlElem$ButtonCompletedProjects','')">Show Completed Projects</a>
<a id="p_lt_ctl01_pageplaceholder_p_lt_ctl02_IssuesSettings_userControlElem_ButtonClosedIssues" class="btn btn-default btn-xs" href="javascript:__doPostBack('p$lt$ctl01$pageplaceholder$p$lt$ctl02$IssuesSettings$userControlElem$ButtonClosedIssues','')">Show Closed Issues</a>
</div>
Notice how _doPostBack is within the href attribute on both anchor elements. Now, checkout the button.js plugin, you'll see the following lines:
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault() // here's the issue
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
On line 9 (starting from //BUTTON DATA-API) you'll see e.preventDefault() being called at the end of the if statement. This is going to prevent the anchor tag from performing its default behavior, which would be to call the _doPostBack function.
If you're having this issue and don't need the button plugin, just remove that plugin from your script. If you do need the button plugin and are having this issue, you'll need to write some logic to handle this. I modified that if statement on line 9 to check for the '.btn-asp' class first and to proceed with default behavior if that was the case, otherwise it proceeds with the button plugin's logic:
if(!($e.target).hasClass(".btn-asp")){
if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault() // here's the issue
}

Async Javascript callback not triggering the RaiseCallBackEvent function

In my asp.net application I used the async javascript callback.
The requirement is once the user enters the Postal code an async javascript callback function should be called. And the server side code must return me the city with respect to the postal code.
The coding I did is:
<asp:TextBox ID="txtPostCode" runat="server" CssClass="textbox" onchange="javascript: getCityAndStreet();" BorderStyle="Ridge" Height="20px" style="margin-left: 10px" Width="442px"></asp:TextBox>
This textbox onchange it will call the javascript function getCityAndStreet()
function getCityAndStreet()
{
var postalCode = document.getElementById('<%=txtPostCode.ClientID%>');
CallServer(postalCode.value, "");
}
function ReceiveCityAndStreet(rValue,context)
{
alert(rValue);
var city = document.getElementById('<%= txtCity.ClientID%>');
city.value = rValue;
}
Here the CallServer is the server side runtime javascript which is registered as below
protected void Page_Init(object sender, EventArgs e)
{
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveCityAndStreet", "context",true);
String callbackScript;
callbackScript = "function CallServer(arg, context)" + "{ " + "alert('Entered inside CallServer' + arg);" + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
}
I implemented the ICallBackHandler and by this I got 2 methods:
string ICallbackEventHandler.GetCallbackResult()
{
return cityAndStreet;
}
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
txtStreet.Enabled = true;
txtCity.Enabled = true;
cityAndStreet = eventArgument;
}
in page_load function I just disabled the txtStreet.Enabled. txtCity.Enabled text boxes and on the raise callbackevent I am enabling it.
The issue here is the RaiseCallBackEvent is not working. I mean its not been triggered implicitly.
(This application is not accessed directly in the browser it is accessed through the SharePoint site)
I think the problem is that your button actually does postback when you click on it. You do not need postback because you are calling server using AJAX. Try changing onchage handler to this:
onchange="getCityAndStreet();return false;"
This will cause your button not to trigger postback.
EDIT: Also i want to mention that you cannot change controls in RaiseCallBackEvent method. It is not an actual postback. You need to enable text fields using javascript in onSuccess method.

Categories