asp.net trigger button click on server side from postback manually - javascript

I have an asp.net page. & I am using jquery confirm plug in from here.
https://craftpip.github.io/jquery-confirm/
I want that when user clicks a button, they are prompted for a confirm dialog & when they say confirm,only then my button click on server should get fired. I do not want to use the window.confirm dialog.
I was able to use jquery confirm & called postback manually via Button's ClientClick property.
The __doPostBack event is firing. However, the click event on server side for the button is not getting fired.
What am i missing ?
ASPX Code :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Tester.aspx.cs" Inherits="BLF_Gauri.Tester" %>
<html>
<head>
<script src="Scripts/jquery-2.1.0.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.3/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.3/jquery-confirm.min.js"></script>
</head>
<body>
<form runat="server">
<asp:Button ID="Button2" runat="server" Text="YEs" OnClick="Button2_Click"
OnClientClick="return TestClick(this);" />
</form>
<script type="text/javascript">
function TestClick(x)
{
jQuery.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
__doPostBack("'" + x.id + "'", 'OnClick');
},
cancel: function () {
// Do Nothing
}
}
});
return false;
}
</script>
</body>
</html>
The Code Behind : (Simplified)
protected void Page_Load(object sender, EventArgs e)
{
//IT COMES HERE.
}
protected void Button2_Click(object sender, EventArgs e)
{
//IT DOES NOT COME HERE.
}

So I solved this!! Instead of using __dopostback I used this.
WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions("" + x.name + "", "", true, "", "", false, true));
x.name coz inside a master page. id changes.

Related

how to pass value from javascript to ASP control

Good day,
Been new to web development (i use ASP.NET) and i had this goal of passing/returning a value to display on HTML element such such as input. I had done searching and trying most of the solutions i found but none work, the output still returns an empty value on the HTML input. why is that? my code i'm working on can be seen below:
javacript:
function confirmExistence(entityValue) {
var entity = "Staff";
var result = "";
if (entityValue === '0') {
entity = "Student";
}
if (confirm(entity + " w/ same name is already registered. is this a different " + entity + "?")) {
result = "Yes";
} else {
result = "No";
}
alert(result);
document.getElementById('<%= fieldFirstNameStudent.ClientID %>').value = result;
}
html:
<asp:button class="by-button" id="btnStudentEnc" runat="server" text="Encode" OnClick="btnStudentEnc_Click" />
<asp:textbox type="text" class="mfield" placeholder="First Name" id="fieldFirstNameStudent" runat="server" />
asp c#:
protected void btnStudentEnc_Click(object sender, EventArgs e)
{ **some sql database condition here to run the clientscript below**
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true); }
Result is as follows on this image:
UPDATE: IF ABOVE IS TOO COMPLICATED. i created a new web form having simple block of codes that still doesn't work
Aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="LobbyStudents.aspx.cs" Inherits="LobbyStudents" %>
<asp:Content ID="Content0" ContentPlaceHolderID="title" Runat="Server">
LobbyStudents
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:textbox placeholder="First Name" id="fieldFirstNameStudent" runat="server"/>
<asp:button runat="server" text="Encode" OnClick="btnStudentEnc_Click"></asp:button>
</asp:Content>
Aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class LobbyStudents : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnStudentEnc_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true);
}
}
ClientScript works and even does the alert box. Still textbox is still empty and doesn't contain "whatswrong?" value
unlike i try it on this one:
<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="myText" value="tch">
<p>Click the button to change the value of the text field.</p>
<button onclick="confirmExistence('0')">Try it</button>
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("myText").value = "whatswrong?";
}
</script>
</body>
</html>
where it works.
What's the difference between the two and why it doesn't happen on asp controls
ok, figure out what is the issue for your first example, is not related to the position, but
change your
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
to
document.getElementById("<%= fieldFirstNameStudent.ClientID %>").value = "whatswrong?";
this will generated in html as
document.getElementById("System.Web.UI.WebControls.TextBox").value = "whatswrong?";
which the js not able to find the control name as System.Web.UI.WebControls.TextBox
if assign with .ClientID, it will generate the correct id
document.getElementById("MainContent_fieldFirstNameStudent").value = "whatswrong?";

Uncaught ReferenceError: show value is not defined(Only for mobile device)

Hi I had implemented the code in which on adding to cart the item gets add and also one popup gets open which shows cart item.
On desktop it is working well but on mobile device it is not working.
For mobile device it is shoeing error as
Uncaught ReferenceError: showvalue is not defined
Here is my below code
<script type="text/javascript">
function showvalue(value, product) {
$('#<%= lblproduct1.ClientID %>').text(product);
$('#<%= lblVessel.ClientID %>').text(value);
$('.cart_popup').show();
setTimeout(function () {
$('.cart_popup').fadeOut('slow');
}, 5000);
return false;
}
function Showprogress() {
$('#<%= Progress.ClientID %>').show();
}
Html side on .ascx page
<asp:Button ID="AddToBasketButton" OnClientClick="Showprogress()" runat="server" OnClick="AddToBasketButton_Click" EnableViewState="false" ValidationGroup="AddToBasket" Text="Add to Cart" />
My .cs side code (Passing total and productquantity)
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel), UniqueID, "showvalue('" + Total + "','" + productquantity + "');", true);
I am facing issue for mobile device only.
On clicking button my page get refresh and popup is not getting open
I had remove jquery popup and made use of Ajax Modal popup.
The popup was opening fine as I was calling it from .cs side but to hide it automatically after 5 second it was not working in that case I had used below code.
<asp:Button ID="AddToBasketButton" OnClientClick="Showprogress();" runat="server" OnClick="_Click" Text="button" />//button click and onclient click
//Below div is only showing processing image :-)
<div id="Progress" runat="server" style="display: none;">
<img src="../images/spinner.gif" />
</div>
My script
<script type="text/javascript">
$(document).ready(function () { hide_pop(); });
function Showprogress() {
$('#<%= Progress.ClientID %>').show();
hide_pop();
return false;
}
function hide_pop() {
setTimeout(function () {
$('.popup_cart_main').fadeOut('slow');//Popup Panel class
$('.modalBackground').fadeOut('slow');//Background blacklayout Class
}, 5000);
return false;
}
Modalpopup
<asp:LinkButton ID="lnkDummy" runat="server" ></asp:LinkButton>
<cc1:ModalPopupExtender ID="ModalPopupExtender1" BehaviorID="mpe" runat="server"
PopupControlID="pnlPopup" TargetControlID="lnkDummy" BackgroundCssClass="modalBackground" >
</cc1:ModalPopupExtender>
<asp:Panel ID="pnlPopup" runat="server" CssClass="popup_cart_main" Style="display: none">
<div class="cart_popup" >
Solved
</div>
</asp:Panel>
This code is working in all browser and all mobile including iphone & Android
I also think(According to actual question) that in case if I had not removed jquery popup and only placed below code my popup had been started working in mobile too
$(document).ready(function () { showvalue (); });// based on actual question
Ensure that your script is rendered before calling RegisterClientScriptBlock. HTML parsing is linear.
Did you miss to copy the closing tag or you just didn't do it on code too?
It should be:
<script type="text/javascript">
function showvalue(value, product) {
$('#<%= lblproduct1.ClientID %>').text(product);
$('#<%= lblVessel.ClientID %>').text(value);
$('.cart_popup').show();
setTimeout(function () {
$('.cart_popup').fadeOut('slow');
}, 5000);
return false;
}
function Showprogress() {
$('#<%= Progress.ClientID %>').show();
}
</script>
Try another approach:
In javascript:
<script type="text/javascript"> var jName = '<%=cName()%>'</script>
In c#:
protected string cName() {
return "examplevarcontent";
}

HTML button sending input text data to ASP side

I am working on a group project, and am trying to figure out ASP.net (hardly anyone in my group knows it, including me). My job is to make some text box and button such that, when the button is clicked, the text in the text box is processed and posted iff it has <= 140 characters.
I tried to write some jQuery that checks the text in the text box, and then sends it to the server for processing. The server is to save it to database, and post it to page, if it is no more than 140 characters long (this will be checked again).
Unfortunately, I run into this error. I tried to contact my team members, but they are super busy with other issues. Here is my code:
Feed.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Feed.aspx.cs" Inherits="Feed_Feed" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<!-- This is here for test purpose -->
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(
function()
{
$('#TweetButton').click(
function()
{
// get the text from the TweetBox
var status = $('#TweetBox').val();
// if it is 140 characters or less
if (status.length <= 140)
{
var data = JSON.stringify(status);
// send to the server page
$.ajax({
url: '/Feed.aspx.cs',
type: 'POST',
dataType: 'json',
data: data,
success: function(myStatus)
{
$('#MyStatus').html(myStatus);
}
});
}
else
{
alert("Tweet should contain no more than 140 characters");
}
});
});
</script>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<h1>User Feed</h1>
<p>
<input id="TweetBox" type="text" /><input id="TweetButton" type="button" value="button" />
</p>
<div id="MyStatus"></div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="LeftContent" Runat="Server">
</asp:Content>
Feed.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Feed_Feed : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
The C# file is practically empty because I don't know how to handle the data being posted to the page (should it be in Page_Load?) I don't know what to do here...
The code is not going to post data to the asp.net server because you are just using regular HTML elements. In order to convert an html element to asp.net element, you need to use attribute runat="server", so your markup would become :
<input id="TweetBox" type="text" runat="server" /><input id="TweetButton" type="button" value="button" runat="server" />
Alternately, to make the job simpler and have more flexibility on the asp.net controls ( like accessing additional properties ), you should strictly use asp.net core controls. So your new markup would look like :
<asp:TextBox id="TweetBox" runat="server"></asp:TextBox>
<asp:Button id="TweetButton" runat="server"></asp:Button>
In order to trigger a click event to post data onto the server ( codebehind ), you need to add the attributes OnClick to your button.
<asp:Button id="TweetButton" runat="server" OnClick="TweetButton_Click"></asp:Button>
In the codebehind (*.aspx.cs), you need to handle the event triggered by the button and check for the length of the text.
public partial class Feed_Feed : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TweetButton_Click(object sender, EventArgs e)
{
if(TweetBox.Text.Length <= 140)
{
// Save data in the database.
}
}
}
UPDATE :
To work with ajax, you would need asp.net controls, so your markup would be
.ASPX =>
<input id="TweetBox" type="text" />
<input id="TweetButton" type="button" value="button" />
<script>
$().ready(function()
{
$('#TweetButton').click(function(){
// if it is 140 characters or less
if (status.length <= 140)
{
// send to the server page
$.ajax({
url: '/Feed.aspx/SubmitTweet',
type: 'POST',
dataType: 'json',
data: "{'tweet':'" + $('#TweetBox').val() + "'}",
success: function(myStatus)
{
$('#MyStatus').html(myStatus.d);
},
error : function(er)
{
}
});
}
else
{
alert("Tweet should contain no more than 140 characters");
}
});
});
</script>
.ASPX.CS ( code-behind ) =>
[WebMethod]
public static string SubmitTweet(string tweet)
{
// dummy function :
return DataSubmit(tweet) ? "Data Was submitted" : "Error while submitting data";
}
public bool DataSubmit(string data)
{
//call db connection and save the tweet
// if successful , return true else false
}

sending 'this' as parameter from web controls to javascript functions

i have a function like this:
<script type="text/javascript" >
function postBack(e) {
var lnk=document.getElementById('<%=e.getAttribute("ClientID") %>');
lnk.click();
};
</script>
and have a link button like this:
<asp:LinkButton onfocus="postBack(this);" id="lnk_home" runat="server"
AccessKey="h" onclick="lnk_home_Click">Home</asp:LinkButton>
I want to redirect page when i press Alt+h
But it does not work. I get the following error when i press Alt+h:
[Compiler Error Message: CS0103: The name 'e' does not exist in the current context]
Any suggestions about how to fix this problem? Thanks
UPDATE**
Server side code:
protected void lnk_home_Click(object sender, EventArgs e)
{
home home_view = LoadControl("home.ascx") as home;
Panel pnl_view = (Panel)ContentPlaceHolder1.FindControl("pnl_view");
//pnl_view.Controls.Clear();
pnl_view.Controls.Add(home_view);
}
You don't need a separate JavaScript function, just use this.click():
<asp:LinkButton onfocus="this.click()" id="lnk_home" runat="server" AccessKey="h" onclick="lnk_home_Click">Home</asp:LinkButton>
Or if you do want to use a separate function (perhaps to perform some common routine on multiple LinkButtons) invoke click method on passed object itself:
<asp:LinkButton onfocus="postBack(this);" id="lnk_home" runat="server" AccessKey="h" onclick="lnk_home_Click">Home</asp:LinkButton>
<script type="text/javascript" >
function postBack(oLink) {
// some common code
oLink.click();
};
</script>
UPDATE When you actually click the link with the mouse - event may fire twice, so you need to limit it to one click:
<asp:LinkButton onfocus="this.AllowClick=true;this.click();" OnClientClick="if (this.AllowClick) {this.AllowClick=false} else {return false}" id="lnk_home" runat="server" AccessKey="h" onclick="lnk_home_Click">Home</asp:LinkButton>

BlockUI during partial postback through JavaScript

I have an ASP.NET page (WebForm1) that opens a modal dialog WebForm2 (via OpenForm2() js function) for some further processing. Upon closing the dialog I just update the UpdatePanel via JavaScript. Now the problem is, during this js call it doesn't block the UI.
This is only happening when I am calling the OpenForm2 js method from the server side (Button1_Click). As the UI already went into block mode, upon closing the WebForm2 it doesn't wait for the completion of partial postback (JavaScript) and unblocks the UI.
If I directly call the OpenForm2 js function in OnClientClick tag of the button (Button 2 in the sample), it works well and keeps blocking the UI till completion of postback.
I tried wrapping the partial postback js code in an add_endRequest, but in that case it keeps calling the refreshUpdatePanel() js method, hence blocking/unblocking the UI keeps going on. May this be happening due to two add_endRequest used on a page in that case?
Any assistance is highly appreciated in this regard.
NOTE: I have used jQuery blockUI for blocking the page during partial postbacks.
The code sample for the WebForm1 page is as follows. (The WebForm2 aspx page just have a button to close the dialog and a related js function).
WebForm1.aspx
<head runat="server">
<title></title>
<script src="js/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="js/jquery.blockUI.js" type="text/javascript"></script>
<script type="text/javascript">
function OpenForm2() {
var url = "WebForm2.aspx";
var width = 950;
var height = 455; // screen.availHeight - (120 + 65);
// open modal dialog
obj = window.showModalDialog(url, window, "dialogWidth:" + width + "px; dialogHeight:" + height + "px; center:yes");
// partial postback to reflect the changes made by form2
refreshUpdatePanel();
//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(refreshUpdatePanel);
// ** here it doesn't wait for the completion and unblocks the UI **
}
function refreshUpdatePanel() {
//window.__doPostBack('UpdatePanel1', '1');
// a timeout/delay before a client side updatepanel postback. That compelled the UI to go in blocking again with a little screen flickering.
setTimeout('__doPostBack("<%= UpdatePanel1.ClientID %>", "1")', 0);
}
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
$.blockUI.defaults.css = {};
function InitializeRequest(sender, args) {
// Whatever you want to happen when the async callback starts
$.blockUI();
}
function EndRequest(sender, args) {
// Whatever you want to happen when async callback ends
$.unblockUI();
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_Load">
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text=""></asp:Label><br />
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClientClick="OpenForm2();return false;" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
WebForm1.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
// some server side processing here
System.Threading.Thread.Sleep(1000);
// then calling javascript function to open form2 as modal
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "Button1Click", "OpenForm2();", true);
}
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
if (parameter == "1")
{
System.Threading.Thread.Sleep(3000);
Label2.Text = DateTime.Now.ToString();
}
}
use
function refreshUpdatePanel() {
__doPostBack"<%= UpdatePanel1.ClientID %>", '1');
}
instead of
function refreshUpdatePanel() {
window.__doPostBack('UpdatePanel1', '1');
}
thank you

Categories

Resources