asp.net Button event inside jQuery FaceBox [duplicate] - asp.net

This question already has answers here:
Facebox adding commas to input
(3 answers)
Closed 3 years ago.
I'm using jQuery FaceBox to show a textbox, a dropdownlist and a button. The user can write a text in the textbox, select a value in the ddl abd hit the button. This fires some code in the codebehind. The FaceBox shows fine, and the content in it is also ok. Also, the button event is fired. This is the code for the button event handler:
protected void Button1_Click(object sender, EventArgs e)
{
_favorit = new Favoritter();
ListItem fav = ddl_favoritter.SelectedItem;
_favorit.FavoritterFolderID = int.Parse(fav.Value);
//_favorit.FavoritterFolderID = Convert.ToInt32(ddl_favoritter.SelectedItem);
_favorit.FavoritterNavn = txt_favoritNavn.Text;
_favorit.FavoritterUserID = UserID;
_favorit.FavoritterUrl = HttpContext.Current.Request.Url.ToString();
FavoritterManager.InsertFavoritter(_favorit);
}
A business object is created, and its properties set with the values read from the controls. The object is then inserted into a database, which works just fine. The problem is that the textbox and dropdown values are not set properly. The textbox value is empty, and the ddl selected value is allways 1, even though I write in the textbox, and select another ddlitem before I hit the button. The ddl is loaded like this:
if (!Page.IsPostBack)
{
_favoritter = FavoritterFolderManager.GetFavoritterFolderByUser(UserID);
ddl_favoritter.DataSource = _favoritter;
ddl_favoritter.DataBind();
}
I tried putting this code outside if (!Page.IsPostBack), and also filling it using an objectdatasource, still the same issue. It's like the controls are "reset" as I hit the button, and I don't think it has anything to do with the FaceBox, as all it does is to show the div that contains the controls... Then again, it might... Any ideas?
This is the code in the aspx page:
<div id="showme" style="display:none;">
Add to favourites.<br />
<br />
<p>
Title: <span><asp:TextBox ID="txt_favoritNavn" runat="server"></asp:TextBox></span></p>
<p>
select folder: <span><asp:DropDownList ID="ddl_favoritter" runat="server" DataTextField="FavoritterFolderNavn"
DataValueField="FavoritterFolderID" AppendDataBoundItems="true">
</asp:DropDownList>
</span>
</p>
<br />
<asp:Button ID="Button1" runat="server" Text="Gem" onclick="Button1_Click"/>
</div>

You need to have the code that fills the text box and selects the drop down item inside of the if(!IsPostBack) block, because the page load event fires again before the button event (See the ASP.NET Page Life Cycle for more info on this). Have you tried enabling view state on the control? That may be part of the issue.

Change
$('body').append($.facebox.settings.faceboxHtml)
to
$('form').append($.facebox.settings.faceboxHtml)

The problem is a lot of these controls, not just FaceBox append themselves to the body by default. jQuery UI dialog does this as well.
See this question for a fix: JQuery Facebox Plugin : Get it inside the form tag
When things happen outside the <form> tag, they're disconnected from how ASP.Net works. When you clicked submit, the values from those inputs weren't inside the form, so didn't submit to the server...which is why you aren't seeing the values.
This is the quick answer from that question, credit to Kevin Sheffield:
poking around the facebox.js I came across this line in the function init(settings)...
$('body').append($.facebox.settings.faceboxHtml)
I changed that to ...
$('#aspnetForm').append($.facebox.settings.faceboxHtml)

Related

how to make enter key click on different buttons depending on which field is empty?

I have a web form in asp.net coding with vb and it has multiple textboxes and buttons. If one textbox is empty, I would like one button to be clicked if the enter key is pressed, whereas if a different textbox is empty, I would like the other button to be clicked, when the enter key is pressed. I know I can change the default button in the form section, but I don't know how I could go about changing the default button depending on which textbox is empty? I assume I have to do this in javascript, which I have little understanding of so any help would be much appreciated.
Can I do something like this to change the default button?
If txtMembranePressure.Text = "" Then
Dim sb As New System.Text.StringBuilder()
sb.Append("<form id='form1' runat='server'" + "defaultbutton='btnMembranePressure'")
Else
Dim sb As New System.Text.StringBuilder()
sb.Append("<form id='form1' runat='server'" + "defaultbutton='btnDiamondPressure'")
End If
Could I put the default button directly on the form like this?
Would it not be better to have one click routine - all buttons can freely point to that one click routine - but inside of that click routine, you can freely check the value(s) of the given text boxes, and then run the desired code. This seems a whole lot less complex then trying to change what actual button supposed to be clicked. So, have all buttons run the SAME routine, but that routine can simple check which text boxes have values in them.
Then based on what text boxes have (or have not) a value, you simple run or call the code you want based on this information.
Keep in mind, that in most cases, hitting enter key will trigger the button that FOLLOWS the control in the markup after that text box.
Edit: correction: the FIRST button on the page will trigger.
However, you can TURN OFF this behavour by setting in the button markup usesubmitBehaviour=False
<asp:TextBox ID="txtSearchOC" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button"
UseSubmitBehavior="False" />
In fact, if you drop a text box on a form, then say a gridview with 10 rows, and each row of the gridviewe has button with click event? Hitting enter key in above will in fact trigger the FIRST row button click of the gridview!!!
So, often by correct placement of buttons, say like a search text box, and a button after to click "search data", then in fact, if they hit enter key, the button that follows that text box will trigger anyway. (as noted, first button on markup fires - not any button, or not actually the one that follows the textbox).
So, in some cases, the correct order of a text box, and the button that follows can be put to good use here. But, often it can surprise you. You drop in a text box, and a form has 10 buttons that follow, ONE of them WILL trigger when you hit enter key - and this can often be harder to PREVENT this from occurring.
So, keep the above in mind. but, given that you want code to run based on values in text boxes (or lack of values), then I would have ONE routine that the button clicks ALL use, and the code behind can then check the text box values, and take the desired course of action and run your desired code based on this information.
There are 3 steps to do.
You need to know, when a Textbox is changed. For that you can use the TexboxChanged Event.
You need to know, if the Textbox is empty.
You need to know, how to change the default button.
Every Textbox need a TextboxChanged Event. And in every event you should check, if the Textbox is empty. If it is empty, you should set it to default.
In Pseudocode:
if Textbox.Text = "" then
set Textbox to default
For further information on the Textbox Change EVent, search in a searchengine (for example duckduckgo.com) for "textbox changed event":
https://meeraacademy.com/textbox-autopostback-and-textchanged-event-asp-net/
To change the default button, please consider following Answers at Stackoverflow:
How to set the default button for a TextBox in ASP.Net?
I have provided you with sufficient detail and example code below to re-engineer this yourself, even if I have not quite understood your requirement. I do agree with the comments above, this is probably not the best approach. You are better off checking server-side whether text boxes are populated or not, and then following a different path in your code.
JQuery lets you find elements by class name (CssClass="" in .NET, class="" on a normal HTML element)
$(".ClassName") makes JQuery find all elements with that class name on the page.
$("#Id") makes JQuery find all elements with that Id on the page.
data-whatYouWantToStore is a convenient way of storing data against an element, that you can then read with Javascript / JQuery. Just keep it all lower case to avoid upsetting it.
$(element).data("the name after the data- bit") will get you the value.
The only bits you need to change to make it run are on the text-boxes:
data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"
Set the class of the button you want it to click when enter is pressed, if the textbox is empty in the data-targetbuttonemptyclass property, and the button to click if text is present in the data-targetbuttonnotemptyclass property. Text boxes must have the class js-click-if-not-empty set on them if you want them to be handled by the "empty / not empty" JavasScript.
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Buttons.aspx.vb" Inherits="Scrap.Buttons" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<!--Add reference to Jquery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!--Your Javascript -->
<script type="text/javascript">
$(document).ready(function () {
// find all the buttons we want to set this behaviour on
$(".js-click-if-not-empty").each(function () {
// add a keypress event hander to each button
$(this).on("keypress", function () {
// get the key that was pressed
var keycode = (event.keyCode ? event.keyCode : event.which);
// is it the ENTER key?
if (keycode === 13) {
// prevent anything else that was going to happen because enter was pressed.
event.preventDefault();
// is the textbox empty?
if ($(this).val() === "") {
// yes - get the css class of the button to click when the textbox is empty
var button = $("." + $(this).data("targetbuttonemptyclass"))[0];
// just for debugging to show which button is about to be clicked
alert("going to click empty button: " + button.id);
// click the button
button.click();
} else {
// no - get the css class of the button to click when the textbox is not empty
var button = $("." + $(this).data("targetbuttonnotemptyclass"))[0];
// just for debugging to show which button is about to be clicked
alert("going to click not empty button: " + button.id);
// click the button
button.click();
}
};
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="tb_TextBox1" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
<asp:TextBox ID="tb_TextBox2" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
<asp:TextBox ID="tb_TextBox3" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
<asp:Button ID="btn_ClickIfEmpty" runat="server" CssClass="js-button-1" Text="Click If Empty" />
<asp:Button ID="btn_ClickIfNotEmpty" runat="server" CssClass="js-button-2" Text="Click If Not Empty" />
</div>
</form>
</body>
</html>

Getting a Bootstrap Modal to open when Asp.net Drop Down List Item Selected

So my issue is that I have an Asp.net Drop Down List control with a listing of names, and the last option opening a modal when selected to add new name. I currently show and hide a div, but I am converting my app to bootstrap and I can't seem to get the bootstrap modal to work as I'd like.
Currently my modal div is as follows:
<asp:Panel ID="AddPOCPanel" runat="server" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">...</asp:Panel>
And in my code-behind, when I populate my drop down list I add the necessary attributes per the bootstrap api:
var add = new ListItem("Add Point of Contact");
add.Attributes.Add("data-toggle","modal");
add.Attributes.Add("data-target","#AddPOCPanel");
Here's the signature of my DropDownList:
<asp:DropDownList ID="POC1DropDownList" runat="server" AutoPostBack="true" class="form-control" OnSelectedIndexChanged="POCDropDownList_SelectedIndexChanged">
</asp:DropDownList>
I've tried a number of things and made some observations:
This seems to be unique to the "option" element, in that if I try to use a link or button in place of the dropdown option, it works just fine. So is an option's behavoir not allow me to do what I am attempting?
I am using AutoPastBack="true", which "overrides" the modal, but removing this has no effect.
I found the solution. I was making it more difficult on myself than necessary, instead of manipulating the DropDownList option for "Add Point of Contact" I did the following:
When the user selects the last option to add a contact, I looked at the value selected in my postback (note that I am using AutoPostBack="true"), and if it was the "Add Point of Contact" option then I did the following:
Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowModal", "$('#AddPOCPanel').modal('show'); $('#MainContent_POC1DropDownList').val('');", false);
This is a great solution, as it works with behavoir of webforms well, for example if using validators, you can do the following:
protected void SomeButton_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Do work then...
Page.ClientScript.RegisterStartupScript(this.GetType(), "HideModal", "$('#AddPOCPanel').modal('hide'); $('#MainContent_POC1DropDownList').val('');", true);
}
else
{
//Make sure modal stays open...
Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowModal", "$('#AddPOCPanel').modal('show'); $('#MainContent_POC1DropDownList').val('');", true);
}
So hopefully this helps anyone finding themselves in the same bind down the road...

Executing Javascript code after submission of asp.net form

How do I execute Javascript after submission of an ASP.NET form?
For example, if I got a submit button click after submission of page then I want to display a DIV which I have hidden on page.
Since you are using a full postback, you can easily include the javascript from the code-behind.
Place your JavaScript Code inside a Placeholder
<asp:Placeholder ID="javascriptPlaceholder" runat="server" Visible="false">
<%-- Your Javascript here -->
</asp:Placeholder>
I assume in your OnClick handling method, you are getting the value of the form and do something else with it. In this method you could set the Visibile property of the placeholder:
this.javascriptPlaceholder.Visible = true;
If you would only want to convert the hidden div to a visible one then that can be done on the server side. In the aspx, give the div an id and a runat="server". Then in the server side, set its display style attribute to 'block'. For example, say the div is defined as
<div id="divTest" runat="server" style="display:none;">
This is a div test
</div>
Then in the post event of the submit button you can set its style as given below:
divTest.Style["display"] = "block";
If you only want to emit scripts after the post then using the ScriptManager you could use:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ScriptRegisterTest", "alert('Testing');", true);
Maybe I'm not understanding your question, but if you're going back to the server and doing some processing, why do you need javascript? Just add a runat="server" to the div in question and make it visible after the processing.
<div id="YourDiv" runat="server" Visible="false" >
...Whatever is here
</div>
Code Behind:
protected void Button_Click(object sender, EventArgs e)
{
/*
Your Logic Here
*/
YourDiv.Visible = true;
}

How to prevent form's action to occur in asp.net

I have a form with action="xyz.aspx:type=new" and some input textboxes and 2 buttons: Submit and Preview. The Submit button updates the database with textbox values and Preview button carries the form textbox values to page "xyz.aspx?type=preview" . The problem is that the functiobalities are achieved but after clicking Preview button, the form's action url gets into action and causes an update in the database which is not wanted. So how do I prevent this from happening? ANy help is appreciated.
If your two buttons are not asp:Buttons, do that first.
<asp:Button Id="Submit" runat="server" OnClick="Submit_OnClick"/>
<asp:Button Id="Preview" runat="server" OnClick="Preview_OnClick"/>
Now, move your code to update the database into Submit_OnClick
protected void btnExecute_Click(object sender, EventArgs e)
{
//update your database
}
Your database should only be updated when Submit is clicked.
If you need your Preview button to post to another page, use the PostBackUrl property.

How do I target a GridViewRow with an AJAX.Net Toolkit PopupExtender?

I have a lot of data to display in a GridView. Because there's so much information per row, I'd like to be able to display additional information when a user clicks on the row, so I thought a PopupExtender from the AJAX Toolkit would be perfect.
Ideally, I want the popup to display whenever any of the controls within the row are selected. I've been able to successfully attach the PopupExtender to a single control within the row, but I can't get the pop-up to attach to the row itself.
I would have thought that setting the PopupExtender's TargetControlId to the Row's ClientID within the RowDataBound event would work, but when I do this I get a runtime error:
TargetControlID of 'popupExtId' is not valid.
A control with ID 'gvList_ctl02' could not be found.
I noticed that the GridViewRow is rendered, the tr element does not include an id, so I also tried extending the GridView control to override the CreateRow method to render the id - using this method I was able to render the row's ID (e.g. gvList_ctl02), but the same runtime error was thrown when I added the PopupExtender back into the code.
I also tried binding the showPopup() javascript command to the row's onclick event to get the popup to display manually; whilst the click event is registered OK and is definitely triggered, the popup is still not shown.
Does anyone have any idea how to / if you can bind a PopupExtender to a GridViewRow?
My row bound code is as follows:
protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Bind the popup extender's target ID to the row ID
// This will cause a runtime error
PopupControlExtender pop = e.Row.FindControl("popupExtId") as PopupControlExtender;
pop.TargetControlID = e.Row.ClientID;
// Also bind the client side click handler to try to get the popup to show
// The alert is triggered and no javascript error is generated, but the popup does not display
e.Row.Attributes.Add("onclick", "alert('Row Clicked'); $find('" + pop.BehaviorID + "').showPopup();");
}
}
Many thanks.
If you're not opposed to using an ajax ModalPopupExtender, I use a little bit of javascript and some sneaky hidden button clicks to fire off my modal popups from within a grid view. I usually make my modal popup extender's target control id my hidden button, then, via javascript, fire my hidden button's click event to show the modal popup.
Here's my modal popup and hidden button markup.
<asp:Button ID="hiddenButton" runat="server" Text="" style="display:none"></asp:Button>
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender2" runat="server"
TargetControlID="hiddenButton" PopupControlID="Panel1" CancelControlID="CancelButton"
BackgroundCssClass="modalBackground" Drag="True"/>
Here's my javascript to show my popup.
function showModal(btnID) {
btn = document.getElementById(btnID);
btn.click();
}
In my rowdatabound event, I call the javascript function showModal from button's onclick event.
Button myButton = (Button)e.Row.Cells[9].Controls[1];
matchButton.Attributes.Add("onclick", "showModal('" + hiddenButton.ClientID + "');");
Hope this might help point you in the right direction.

Resources