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
}
Related
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".
There is a span element that need to load data dynamically from a Repeater control.
The problem that I encounter is only first span element can display the value. The subsequent will display blank.
I've simplify the code behind as below.
private int incre = 0;
protected void Page_Load(object sender, EventArgs e)
{
foreach (RepeaterItem ritem in FeaturedRepeater.Items)
{
HtmlGenericControl span = ritem.FindControl("countdown") as HtmlGenericControl;
span.Load += new EventHandler(test);
}
}
protected void test(object sender, EventArgs e)
{
HtmlGenericControl span = (HtmlGenericControl)sender;
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "timer(" + incre + ")", true);
incre++;
}
Javascript function in .aspx file example as below:
function timer(increment, timespan) {
var id = 'ContentPlaceHolder1_FeaturedRepeater_countdown_' + increment;
document.getElementById(id).innerHTML = id;
}
HTML part:
<asp:Repeater runat="server" ID="FeaturedRepeater" OnItemDataBound="FeaturedRepeater_ItemDataBound">
<ItemTemplate>
<span id='countdown' runat="server"></span>
</ItemTemplate>
</asp:Repeater>
Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("CallMyFunction{0}", incre), "timer(" + incre + ");", true);
you can't register the same key more then one time.
that's why changing "CallMyFunction" to string.Format("CallMyFunction{0}", incre) will work
btw
and ; after every javascript function call.
I'm using div instead of iframe to call a page but as soon as the other page loads in div then after clicking on any button, or selecting radiobutton, these events give this error
This is how I load div
<script type="text/javascript">
$(function () {
setInterval(function () {
$('#result').load('frmChatRequest.aspx', function () {
});
}, 10000);
});
</script>
This is frmChatRequest.aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dt_chatRequest = LookupChat.getPendingRequestInMyChat("",Int64.Parse(_objSession.LoginID), _objSession, _errMsg);
ClsDataBind.DoGridViewBind(gdvChatRequestRoom, dt_chatRequest, _errMsg);
myMarqueeChatRequest.InnerText = "You Have " + dt_chatRequest.Rows.Count.ToString() + " new chat request/s in your rooms in last 15 minutes";
}
}
protected void gdvChatRequestRoom_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Accept")
{
HiddenField hdn = ((HiddenField)gdvChatRequestRoom.Rows[0].Cells[0].FindControl("hdnAddPeople"));
string strHdnValue = hdn.Value;
//Button btn = ((Button)gdvChatRequestRoom.Rows[0].Cells[3].FindControl("btnAccept"));
//string strBtnID = btn.ID;
string strBtnID = e.CommandArgument.ToString();
string query = "select * from Q116 where Q116002="+strBtnID+ " and Q116001="+ hdn.Value ;
_objQ116.SelectAll(query);
_objQ116.Q116DF2 = _objSession.LoginID;
_objQ116.Update(_objQ116.Q116DF2);
_objQ116.SelectAll(query);
_objQ116.Q116004 = DateTime.Now.ToString("hh:mm:ss");
_objQ116.Update(_objQ116.Q116004);
//insert in Q119
// _objQ116.Update(Q116004);
//_objLOG2.SelectAll(query);
//DateTime dt1 = DateTime.UtcNow.AddHours(5.5);
//string str = dt1.ToString();
//_objLOG2.Update(str);
//Write code to add to card
}
if (e.CommandName == "Reject")
{
HiddenField hdn = ((HiddenField)gdvChatRequestRoom.Rows[0].Cells[0].FindControl("hdnAddPeople"));
string strHdnValue = hdn.Value;
//Button btn = ((Button)gdvChatRequestRoom.Rows[0].Cells[3].FindControl("btnAccept"));
//string strBtnID = btn.ID;
string strBtnID = e.CommandArgument.ToString();
string query = "delete from Q116 where Q116001=" + hdn.Value + " and Q116002=" + "'" + strBtnID + "'";
// _objQ116.SelectAll(query);
Educity.EduDB.Select(query);
//Write code to add to card
}
Response.Redirect(Request.Url.AbsolutePath);
}
The ASP.NET webforms JavaScript and markup is probably messing up the hosting page and this is why a whole page is normally loaded in an iframe.
Have you considered using custom controls? They are really easy and encapsulate functionality into objects that can be included in any web page. It looks like frmChatRequest would be better as a control. Building a custom control is very similar to building a aspx webforms page, but it can then be re-used.
For more info on custom controls see http://msdn.microsoft.com/en-us/library/zt27tfhy.ASPX
I have an Asp server control button for which I have onClick for processing code in code behind and onClientClick to process javascript code. The codes are:
Update: As per Icarus solution, updated codes :
Button source:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
style="z-index: 1; left: 648px; top: 202px; position: absolute"
Text="Show route" OnClientClick="droute(); return false" />
<asp:HiddenField ID="hdncroute" runat="server" />
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
using (con = new MySqlConnection("server=localhost; uid=root;password=as64ws;database=Gmaps"))
da = new MySqlDataAdapter("select * from routes where uid='" + Session["uname"].ToString() + "'", con);
da.Fill(ds, "mroute");
foreach (DataRow r in ds.Tables[0].Rows)
{
uroute.Add(r["latlng"].ToString());
}
croute = new string[uroute.Count];
croute = uroute.ToArray();
hdncroute.Value = string.Join("&", croute);
}
Javascript function:
function droute()
{
var route=[];
var temp;
temp = eval(document.getElementById('<%= hdncroute.ClientID %>').value);
route= temp.split('&');
//Polyline icon n line settings
var iconsetngs= {path:google.maps.SymbolPath.FORWARD_CLOSED_ARROW, fillColor:'#FF0000'};
var polylineoptns= {strokeColor:'#3333FF',strokeOpacity:0.8,strokeWeight:3,map:map,icons:[{icon:iconsetngs,offset:'100%'}]};
polyline= new google.maps.Polyline(polylineoptns);
//Loop to add locations and draw line
var path= polyline.getPath();
for(var i=0;i<route.length;i++)
{
var marker= new google.maps.Marker({position:route[i],map:map});
path.push(route[i]);
google.maps.event.addListener(marker,'click',showiwindow);
}
//Event Listener's
function showiwindow(event)
{
iwindow.setContent("<b>Coordinates are:</b><br/>Latitude:"+event.latLng.lat()+"<br/>Longitude:"+event.latLng.lng());
iwindow.open(map,this);
}
}
I know that writing return false for javascript function will avoid refresh, and also onClick has void return type. But still my page reloads on button click.
You have an error here:
route = document.getElementById('<%= croute %>').value;
It should be:
route = document.getElementById('<%= croute.ClientID %>').value;
Update:
Markup - declare a hidden element in the page
<asp:hiddenfield id="hdnCroute" runat="server" />
//code behind
int [] croute = ...
hdnCroute.Value = "["+string.Join(",",croute)+"]";
Now Javascipt:
//now you have an array back in javascript
var route= eval(document.getElementById('<%= hdnCroute.ClientID %>').value);
why the page reload?
OnClientClick="droute(); return false"
at inner of browser like this:
button.onclick = function(){
droute();
return false
};
while droute is going wrong,so,return false doesn't work.
I have a DIV element:
<div runat="server" id="path">Nothing here... yet</div>
and JavaScript which changes its content dynamically. After some actions my element looks like this (tested with Firebug, JS is ok):
<div runat="server" id="path">FirstTest - SecondTest - ThirdTest</div>
Then I'd like to save it to text file (<asp:Button runat="server"...):
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
Button1.Click += new EventHandler(this.GreetingBtn_Click);
}
void GreetingBtn_Click(Object sender, EventArgs e)
{
HtmlGenericControl path = (HtmlGenericControl)Page.FindControl("path");
Response.AddHeader("content-disposition", "attachment;filename=download.txt");
Response.ContentType = "text/plain";
Response.Write(path.InnerText);
Response.Flush();
Response.Clear();
Response.End();
}
</script>
It also works OK (SaveDialog popups, user choose location), but... in output file there's only one line "Nothing here... yet". It looks like he doesn't react to changes made by JavaScript!
How can I force him to refresh DIV, so I can always save up-to-date content?
Thanks for any help!
You could update an asp:Hidden with the new value and use that value instead on the post back. The PlaceHolder control is not designed to be a two-way control.
E.g.
function UpdateText()
{
var text = ...;
document.getElementById("<%= path.ClientID %>").innerText = text;
document.getElementById("<%= pathHidden.ClientID %>").value = text;
}