On a web application, I need to do some conditional logic and then based on that, possibly show a dialog box. Here's what I need to do:
Button pressed, submitting two IP Addresses
Check if these addresses are 'in use'
If they are:
display confirm box
If "OK" is pressed, call C# function
Otherwise, done
If they're not:
Call C# function
When the button is pressed, it calls the clicked method btnLinkConnect_Click() in the C# codebehind. This then checks for addresses 'in use'. Stepping through with the debugger, this all works fine, but if addresses are 'in use', a javascript script is supposed to run to display the box:
<script type="text/javascript">
function askForOverride(station1, station2) {
var answer = confirm("Station(s):" + PageMethods.GetActiveStations(station1, station2) + "is/are in use. Override?");
if (answer) {
PageMethods.uponOverride(station1, station2);
}
}
</script>
But how can I get this script to run from the C# page? I've looked at ClientScript.RegisterStartupScript(), but I couldn't get it to work, and it appears not to be able to work inside the conditionals. I've looked at ajax, but I couldn't understand exactly how to call it from the C# codebehind.
What is the best way to call this script, or obtain the same result, and how should I go about it?
This may work, add some client events for button click based on condition. Please refactor if necessary
protected void btnSumbit_Click(object sender, EventArgs e)
{
//call some function to verify IP entered by user
bool isExistingIp = VerifyIp(txtIP.Text);
if (isExistingIp)
{
// event argument PASSED when user confirm to override from client side
string isoverride = Request.Form["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(isoverride))
{
//register script if user hasn't confirmed yet
this.ClientScript.RegisterStartupScript(this.GetType(), "displaywarning", "displaywarning();", true);
Page.GetPostBackEventReference(btnSumbit);
}
else
{
//continue with functionality
}
}
else
{
//continue with functionality
}
}
On client side add javascript to display warning and do a post back
function displaywarning() {
var isOverride = window.confirm("do you want to override");
if (isOverride) {
__doPostBack('<%=btnSumbit.ClientID%>', 'override');
}
}
You can easily do this with jQuery AJAX calls.
ASPX
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('body').on('click', '.performsMyClickAction', function () {
$.ajax({
type: "POST",
url: "BlogPost.aspx/TestIP",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.d = 1) //In use
{
$("<div>State your confirm message here.</div>").dialog({
resizable: false,
height: 210,
modal: true,
buttons: {
"Ok": function () {
__doPostBack('<%= upnl.ClientID %>', 'InUse ');
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
} else {
__doPostBack('<%= upnl.ClientID %>', 'NotInUse ');
}
}
});
});
});
</script>
<body>
<form id="form2" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="upnl_Load">
<ContentTemplate>
<div>
<asp:Button CssClass="performsMyClickAction" Text="Test IP" ID="Button3" runat="server" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
C#
protected void upnl_Load(object sender, EventArgs e)
{
string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
if (string.IsNullOrEmpty(eventTarget)) return;
var arg = Request.Params.Get("__EVENTARGUMENT");
if (arg == null) return;
if (!string.IsNullOrEmpty(arg.ToString()))
{
if (arg.ToString().IndexOf("InUse") > -1)
{
//Call C# function for in use.
}
if (arg.ToString().IndexOf("NotInUse") > -1)
{
//Call C# function for not in use.
}
}
}
[WebMethod]
public static string TestIP()
{
//Check for IP status
if (true)
return "1";
//else
//return "0";
}
Hope this will help you.
Have a look at ClientScriptManager.RegisterStartupScript, i think this should work
Related
Im struggling getting this to work the way i need. I have two RequiredFieldValidators and two textboxes (Side note: although i have Javascript below i dont mind doing this in another way. I did try code behind but realised validation didnt kick in until i clicked a button twice):
<asp:TextBox ID="EmailTextbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailR" runat="server" ErrorMessage="Email" ControlToValidate="EmailTextbox" ></asp:RequiredFieldValidator>
<asp:TextBox ID="NameTextbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="NameR" runat="server" ErrorMessage="Enter your name" ControlToValidate="NameTextbox" ></asp:RequiredFieldValidator>
I then have some script
<script type="text/javascript">
$(document).ready(function () {
$('#<%=EmailTextbox.ClientID%>').keyup(function () {
if ($(this).val() != '') {
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), true);
}
else
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), false);
});
});
</script>
What im trying to do is:
If EmailTextbox has an email then disable NameTextbox validation.
If EmailTextbox has NO email then enable NameTextbox validation and disable EmailTextbox validation.
With me being pretty new to JQuery/Javascript i have tried several attempts in trying to achieve the above however reading more into it, theres a possibility that i could have the wrong JQuery file (that said with this being an existing project i havent really added any ref to any JQuery so it could well be that i have the code right but need a ref to a JQuery or need to include a new version).
Overall if i can
Thanks
You can try it
$(document).ready(function () {
$('#<%=EmailTextBox.ClientID%>').keyup(function () {
if ($(this).val() != null && $(this).val().length != 0) {
$('#<%= NameRequiredFieldValidator.ClientID%>').hide();
}
else {
$('#<%= NameRequiredFieldValidator.ClientID%>').show();
$('#<%= EmailRequiredFieldValidator.ClientID%>').hide();
}
});
In your code you make the validation enable wrongly when a email
value was not null disable validation on name and enable for email else viceversa
<script type="text/javascript">
$(document).ready(function () {
$('#<%=EmailTextbox.ClientID%>').keyup(function () {
if ($.trim($(this).val()).length)
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), false);
ValidatorEnable(document.getElementById('<%= EmailTextbox.ClientID%>'), true);
}
else
{
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), true);
ValidatorEnable(document.getElementById('<%= EmailTextbox.ClientID%>'), false);
}
});
});
</script>
You can try this, similar to what you had.
function doSomething()
{
var myVal = document.getElementById('myValidatorClientID');
ValidatorEnable(myVal, false);
}
Or, you could use the visible=true/false on them which renders them inactive (meaning set visible property from code behind).. This might cost you an ajax trip to the code behind using scripmanager and __doPostBack in order to call a server-side function that can than process your logic... A lot of developers don't realize that at least in webforms, you can call your code behind methods from JS, just be very careful - as each call back can get costly...
A good article on communicating from ("front end to code behind via JS") -
http://www.codedigest.com/Articles/ASPNET/320_Doing_or_Raising_Postback_using___doPostBack()_function_from_Javascript_in_AspNet.aspx
Hope that helps or get's you back on the right track!!!
I have this script on a page
<script type="text/javascript">
$(document).ready(function () {
var btnApplyVoucher = document.getElementById('LbtnApplyVoucher');
var voucher = document.getElementById('TxtVoucher');
$("input.voucherCode").bind('keyup paste', function () {
btnApplyVoucher.setAttribute("class", "displayBlack");
});
$("input.voucherCode").bind('blur', function () {
if (voucher.value == '') {
btnApplyVoucher.removeAttribute("class", "displayBlack");
}
});
});
</script>
and I have this textbox which is being manipulated by the above jquery
<asp:UpdatePanel ID="UpdBasket" runat="server">
...
<asp:TextBox ID="TxtVoucher" Text="" runat="server" CssClass="voucherCode" ClientIDMode="Static"/>
...
<asp:LinkButton ID="LbtnUpdateBasket" runat="server" Text="Update Basket" OnClick="LbtnUpdateBasket_Click"/></div>
...
</asp:UpdatePanel>
My problem is when LbtnUpdateBasket is clicked and the update panel updates my jquery stops functioning?! I am not sure what I can do here and nothing I can find on the web is really that helpful to me? I believe my problem is something to do with the .ready() which is running when the page loads but ofcourse this wont run on the update as the whole page doest load, what can i do here?
You need to also fire the jQuery when the update panel updates, as well as when the page loads.
For Example:
<script type="text/javascript">
//Get page request manager
var prm = Sys.WebForms.PageRequestManager.getInstance();
//Add handler for end request (update panel, end update)
prm.add_endRequest(configurePage);
$(document).ready(configurePage);
function configurePage() {
var btnApplyVoucher = document.getElementById('LbtnApplyVoucher');
var voucher = document.getElementById('TxtVoucher');
$("input.voucherCode").bind('keyup paste', function () {
btnApplyVoucher.setAttribute("class", "displayBlack");
});
$("input.voucherCode").bind('blur', function () {
if (voucher.value == '') {
btnApplyVoucher.removeAttribute("class", "displayBlack");
}
});
}
</script>
When you click a button the AJAX request is sent, and then the entire HTML content of the UpdatePanel is re-created based on the results of that request. All of the changes that your JQuery code made will then need to be re-applied. You'll need to ensure that the appropriate code to re-apply those JQuery bindings is run within whatever your link button's click handler is fired.
I need to do a postback and save the data in the screen to session when the screen is closed, for this i am using the onBeforeUnload event, and placed a hidden button in the screen. In the on before unload event I am calling the click event to call the button server event. But the event is not firing. Is anything I am missing here.
<asp:Button Style="display: none" runat="server" ID="btnHidUpdate" OnClick="btnHidUpdate_Click" />
<script type="text/javascript">
$(document).ready(function () {
window.onbeforeunload = updateSessionBeforeUnload;
});
</script>
In .js file:
function updateSessionBeforeUnload() {
var hidUpdate = $('[id$="btnHidUpdate"]')[0];
hidUpdate.click();
}
In .cs code behind:
protected void btnHidUpdate_Click(object sender, EventArgs e)
{
UpdateSession();
}
The problem is that the page loads the next page before it can execute the button click.
Use the Jquery Unload event e.g.
$(function(){
$(window).unload(function(){
// put synchronous code here to persist what you need.
});
});
You can use an Ajax event like Yuriy says however you must set async to false like this:
$.ajax({
type: "POST",
url: "Url/To/Persistance",
dataType: "json",
data : { "data" : "to be persisted"},
async: false
});
EDIT
I would avoid the click event all together and do something like this:
$(function(){
$(window).unload(function(event){
var hidUpdate = $('[id$="btnHidUpdate"]')[0];
__doPostBack(hidUpdate.attr('id'),'');
});
});
However if you must click the button try this
$(function(){
$(window).unload(function(event){
var hidUpdate = $('[id$="btnHidUpdate"]')[0];
hidUpdate.click()
alert(
"Default: " + event.isDefaultPrevented() + "\n" +
"ImedPropStopped: " + event.isImmediatePropagationStopped() + "\n" +
"PropStopped: " + event.isPropagationStopped()
);
});
});
And tell us what the alert says ?
I think the other suggestions here should work fine. I have another suggestion which you can try, and is to use GetPostBackEventReference.
You can see details about it here:
http://msdn.microsoft.com/en-us/library/aa720417(v=vs.71).aspx
You can use jquery trigger("click") function which will call the click event on the button.
In my opinion the problem is that onbeforeunload event handler intended to ask user for confirmation when he want to leave a page. And since updateSessionBeforeUnload method doesn't returns any question string, unloading process continues immediately after this method leaves.
If you can make UpdateSession method static you can call it asynchronously with async jQuery.ajax method call:
<script type="text/javascript">
window.onbeforeunload = foobar;
function foobar() {
$.ajax({
type: "POST",
url: "WebForm2.aspx/UpdateSession",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true
});
}
</script>
[WebMethod]
public static void UpdateSession()
{
}
I have a FB login button and want to bind it to a function but I can't seem to get it work:
<div class="fb-login-button" id="auth-loginlink"></div>
This is the line that I am trying to bind it to my fb-login-button
$("#auth-loginlink").click(function () { grantPermission(); });
<script type="text/javascript">
function grantPermission() {
window.FB.login(function (response) {
// ... login stuffs
}
</script>
It will work if I use a normal hyper link like:
Login
Please kindly advice what am I doing wrong. Thanks.
If it's really a button might as well use the button tag:
<button class="fb-login-button" id="auth-loginlink">Login</button>
Put your javascript inside the script tag, and return false in the handler:
<script type="text/javascript">
$("#auth-loginlink").click(function () { grantPermission(); return false; });
function grantPermission() {
window.FB.login(function (response) {
// ... login stuffs
}
</script>
... also might be a good idea to do $("#auth-loginlink").button() but not totally necessary.
Note: If your html is actually below your javascript code the above will not always work.
I have inline script such as this, which toggles between an edit and a display divs. If it is inside the the UpdatePanel it requires two click before it works. If I remove the UpdatePanel it works fine with a single click.
Edit
Can anyone help please?
Thanks
EDIT:
Edit function:
function edit(e, id) {
var editdiv = $('#' + id).find('.edit');
var cntdiv = $('#' + id).find('.content');
if (editdiv.css('visibility') == 'hidden') {
editdiv.css('visibility') == 'visible'
cntdiv.css('visibility') == 'hidden'
cntdiv.hide();
editbox.show()
}
else {
editdiv.css('visibility') == 'hidden'
cntdiv.css('visibility') == 'visible'
cntbox.show();
editbox.hide()
}
stopEventBubble(e); // Code to cancel event bubbling;
}
Are you using the ScriptManager to register the edit function?
protected void Page_Load(object sender, EventArgs e)
{
string jsEdit = #"function edit(event, id) {}";
ScriptManager.RegisterClientScriptBlock(this, GetType(), "editFunction", jsEdit);
}
If your code is in an external file, you can register it with the ScriptManager or the ScriptManagerProxy in the aspx for your page:
<ScriptManager runat="server" id="ScriptManager1">
<Scripts>
<asp:ScriptReference path="~/js/edit.js" />
</Scripts>
</asp:ScriptManager>
EDIT:
alright, I know what the issue is now. You aren't setting the css visibility to begin with. So either you need to set the css visibility or you can modify your edit function to follow the following logic:
function edit(e, id) {
var editdiv = $('#' + id).find('.edit');
var cntdiv = $('#' + id).find('.content');
//I reversed it to look for visible instead of hidden. The main problem with this approach and your other approach is that the original value is inherited.
if (editdiv.css('visibility') == 'visible') {
editdiv.css('visibility') == 'hidden'
cntdiv.css('visibility') == 'visible'
cntbox.show();
editbox.hide()
}
else {
editdiv.css('visibility') == 'visible'
cntdiv.css('visibility') == 'hidden'
cntdiv.hide();
editbox.show()
}
stopEventBubble(e); // Code to cancel event bubbling;
}
The other option will require you to set the following in you "edit" and "content" divs.
<div id="edit" style="visibility:hidden"> ... </div>
<div id="content" style="visibility:visible"> ... </div>
If you need further help, I'll need to see your aspx code concerning the UpdatePanel, edit, and content.
Try this:
Edit
Edit
As Chris said:
If you are injecting the function when you click the Edit link the function won't exist the first time you click an Edit link.
What you could do is add the function inside a <script> tag in the <head> section of the markup:
<head>
<script>
function edit(event, id) {
// Your code here
}
</script>
</head>
Or in a separate .js file.