I have the following source in aspx:
<div>
<asp:HiddenField ID="hidValue" runat="server" />
<asp:Button runat="server" ID="hidButton" OnClick="hidButton_Click" />
<script type="text/javascript">
function ExtendPanel(PanelNumber) {
var hidValue = document.getElementById('<%=hidValue.ClientID %>');
hidValue.value = PanelNumber;
document.getElementById('<%=hidButton.ClientID%>').fireEvent("onclick");
}
</script>
</div>
In my code behind, I have the following C# function declared:
protected void hidButton_Click(object sender, EventArgs e)
{
int PanelNumber = int.Parse(hidValue.Value);
... do something with PanelNumber ...
}
When I click on the button using the mouse, "hidButton_Click" function is normally executed.
However, when the javascript function ExtendPanel(PanelNumber) is executed, the click event seems to be fired, but the function is not executed.
Replace this
document.getElementById('<%=hidButton.ClientID%>').fireEvent("onclick");
with
__doPostBack('hidButton','OnClick');
try this
document.getElementById('<%=hidButton.ClientID%>').click();
Try this one below
$('#<%=hidButton.ClientID%>').click();
I got the same issues and resolved to put
OnClientClick="javascript:return true;"
Related
<script type="text/javascript">
function GetValue3(id) {
text1 = documnet.getElementById(input parameter from cs file);
alert("this is from cs file");
//database transactions here <-------method1
}
$(function () {
button1 = document.getElementById(input parameter from aspx file);
$("[id*=Button1]").on("click", function () {
alert("this is from aspx file");
//database transactions here <-------method2
})
})
</script>
My question is that there are two procedures for database transactions, first from taking parameters from aspx.cs code befind file and second from aspx file.
In my code i want to do database transactions using second approach (by using parameters from aspx.cs code behind) because it is required in my coding.
please guide me how can i build this approach.
not sure what you are trying to achieve but you need to differentiate between client events and server events
to get element in JS you can get its ID from 'ClientID'
ASPX file:
<asp:TextBox ID="txtTest" OnTextChanged="txtTest_TextChanged" runat="server" AutoPostBack="true" ></asp:TextBox>
<asp:Button ID="btn1" OnClick="btn1_Click" runat="server" Text="Click" />
<script type="text/javascript">
function textFromTextBox() {
var text1 = documnet.getElementById('<%= this.txtTest.ClientID %>');
}
</script>
aspx cs file
protected void btn1_Click(object sender, EventArgs e)
{
var text = txtTest.Text;
}
protected void txtTest_TextChanged(object sender, EventArgs e)
{
var updatedText = txtTest.Text;
}
EDIT:
you cannot attach code behind method to ordinary html element. You can only attach javascript events to these elements or inputs. If its the case then its irrelevant if you are using asp.net web forms, python, ruby on backend server.
<input type="button" id="sbutton" value="Save" />
<script type="text/javascript">
(function (){
documnet.getElementById('sbutton').addEventListener("click", function(){ //do your crud operation });;
})
()
</script>
I have below JavaScript function in my aspx page:
<script>
function ShowMessage() {
alert("Hello World");
}
</script>
I want to use this function in my cs page on button click event:
<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
Now this code works fine:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "alert('Hello World');", true);
But this code dose not work:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "ShowMessage();", true);
What's wrong in my code? What's the possible reason?
You need to expose your ShowMessage() function to a scope that your DOM has access to.
You can try:
window.ShowMessage = function() {
alert("Hello World");
}
Another option is to move your <script></script> containing your function ABOVE the DOM element that needs it:
<script>
function Foo() {
alert('Bar');
}
</script>
<button onclick="Foo()"></button>
You can use onclientclick
<asp:Button ID="MyButton" runat="server" Text="Click Here" onclientclick="ShowMessage()" />
Try this:
<script>
$('#idOfButton').click(
function() {
alert("Hello World");
}
);
</script>
Note: use JQuery for this code and paste this on the end of your HTML page.
Hope this will help
I have used ScriptManager.RegisterStartupScript() method in order to show an alert when particular thing happens in back end.It works fine in page load method but not in particular method which is called when a specific button is clicked . I Couldn't find a solution because in another page it works fine in both page load and the method.
Script Manager RegisterStartupScript Method
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
HTML
<asp:HiddenField runat="server" ClientIDMode="Static" ID="PostBackController"/>
<button class="some-class" id="btnSave" runat="server" onclick="btnSave_clientClick();">SAVE</button>
Javascript
function btnSave_clientClick() {
// code
if (some_condition) {
$('#PostBackController').val("btn_save");
__doPostBack();
}
}
Page Load Method
protected void Page_Load(object sender, EventArgs e)
{
if (PostBackController.Value == "btn_save")
{
uploadDocSave_ServerClick();
}
}
Method Wish should be called when button Clicked
protected void uploadDocSave_ServerClick()
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
}
My deepest condolences for OP if you still have to work with Webforms. This is how you can solve it in a minimal way while reducing traffic:
Codebehind sample:
public partial class About : Page, IPostBackEventHandler
{
protected void Page_Init(object sender, EventArgs e)
{
// Unless the button is serverside clicking it will reload the page
// registering the page like this prevents a page reload.
var scriptManager = ScriptManager.GetCurrent(Page);
scriptManager?.RegisterAsyncPostBackControl(Page);
}
/// <inheritdoc />
public void RaisePostBackEvent(string eventArgument)
{
var javascriptCode = $"alert('server method called and triggered client again. {DateTime.Now.ToString("s")}');";
// if your key isn't changed this script will only execute once
ScriptManager.RegisterStartupScript(udpMain, typeof(UpdatePanel), Guid.NewGuid().ToString(), javascriptCode, true);
// updating the updatepanel will inject your script without reloading anything else
udpMain.Update();
}
}
Webforms sample:
<script type="text/javascript">
function clientFunction(sender, args) {
alert('client function called');
<%= Page.ClientScript.GetPostBackEventReference(Page, "callServerFunction") %>
args.preventDefault();
}
</script>
<asp:UpdatePanel runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional" ID="udpMain">
<ContentTemplate>
<h2><%: Title %>.</h2>
<h3>Your application description page.</h3>
<p>Use this area to provide additional information.</p>
<button onclick="clientFunction(); return false;">raise server function</button>
</ContentTemplate>
</asp:UpdatePanel>
Try this:
If you Used Update Panels Then You can Use:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "javascriptFunction();", true);
Other Wise You can Use
ClientScript.RegisterStartupScript
(GetType(),Guid.NewGuid().ToString(), "javascriptFunction();",true);
Try this:
Client side:
Use Literal Control
<asp:Literal ID="IMsg" runat="server" Text=""/>
Server side:
string msg = "<script>alert('Change successfully');</script>";
IMsg.Text = msg;
I think it will help you. It works fine in my projects.
Try to remove line containing:
__doPostBack();
in the JavaScript code.
Sorry I am late at the party. Use this overload of RegisterStartupScript method, and set the first parameter the button on which you want to click to register the javascript function. Like:
ScriptManager.RegisterStartupScript(btnSave, this.GetType(), "alert", "alert('msg');", true);
Cheers!
THE REALLY SIMPLE WAY
You can wire up a <button runat="server"></button> to a server event using the onserverclick attribute:
HTML:
<button class="some-class" id="btnSave" onserverclick="uploadDocSave_ServerClick" runat="server">SAVE</button>
C# Handler:
protected void uploadDocSave_ServerClick(Object sender, EventArgs args)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
}
WITH CLIENT SIDE VALIDATION
If you want to add some sort of JavaScript check before postback, you can do that from the onclick attribute:
HTML:
<button class="some-class" id="btnSave" onclick="return btnSave_clientClick();" onserverclick="uploadDocSave_ServerClick" runat="server">SAVE</button>
JavaScript:
function btnSave_clientClick() {
// code
if (some_condition) {
return true; // allows the control to do a postback
}
}
C# Handler:
protected void uploadDocSave_ServerClick(Object sender, EventArgs args)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
}
here is example:
abcd.aspx
<asp:TextBox ID="txtFName" runat="server" ></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" Text="Login"
onclick="btnLogin_Click" OnClientClick = "loginAlert()" />
javascriptfile.js
function loginAlert() {
var name = document.getElementById('<% txtFName.ClientID %>').value;
alert(name);
}
link to javascript file on .aspx page
<script src="../../JSfiles/javascriptfile.js" type="text/javascript"></script>
here name is not appear on popup box.
You can't use code nuggets (<% and %>) inside normal files (like your javascriptfile.js) since they're not interpreted by ASP.NET in any way. What you could do is to pass the Id of the text-box to a function:
function loginAlert(ctrl) {
var name = document.getElementById(ctrl).value;
alert(name);
}
Then the markup will look like the following:
<asp:Button ID="btnLogin" runat="server" Text="Login"
OnClick="btnLogin_Click" OnClientClick="loginAlert('<%=txtFName.ClientID%>')" />
UPDATE
I didn't pay attention to the fact that construct like <%=...%> don't work in server-side control declarations (because they're basically converted to Response.Write statements when the page is compiled). There're at least two ways to solve this problem:
You can make the reference to the DOM element for the name text-box globally available. Your markup will look like the following:
<script type="text/javascript">
var loginNameId = '<%=txtFName.ClientID%>';
</script>
<asp:Button ID="btnLogin" runat="server" Text="Login"
OnClick="btnLogin_Click" OnClientClick="loginAlert()" />
And your loginAlert will look like the following:
function loginAlert() {
var name = document.getElementById(loginNameId).value;
alert(name);
}
I personally don't like this solution since you pollute the global namespace with variables and it's not very elegant in general.
Alternatively you can use data attributes together with ASP.NET data binding.
Markup:
<asp:Button ID="btnLogin" data-name='<%# txtFName.ClientID %>' runat="server" Text="Login"
OnClick="btnLogin_Click" OnClientClick="loginAlert(this)" />
JavaScript:
function loginAlert(ctrl) {
var name = document.getElementById(ctrl.readAttribute('data-name')).value;
alert(name);
}
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
DataBind();
}
The javascript file is not served by the ASP.Net parser. Thus, the <% %> is ignored and output as is.
The simpliest way is to provide the ID as parameter:
<asp:TextBox ID="txtFName" runat="server" ></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" Text="Login"
onclick="btnLogin_Click" />
code behind :
btnLogin.OnClientClick = string.Format("loginAlert('{0}')", txtFName.ClientID);
and in the js file:
function loginAlert(txtId) {
var name = document.getElementById(txtId).value;
alert(name);
}
Markup <% %> wont work in JS files. If you put it on aspx page inside <script type='text/javascript'>...</script> then it will work.
Update:
If you want to get client id, then you can register it from code behind in a variable, as:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "JsVariables", "var txtboxClientId='" + txtFName.ClientID + "';", true);
and in Js file use:
function loginAlert() {
var name = document.getElementById(txtboxClientId).value;
alert(name);
}
<asp:ScriptManager ID="ScriptManager1" ScriptMode="Release" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
var elem = args.get_postBackElement();
alert("begin " + elem.value);
}
function EndRequestHandler(sender, args) {
alert("end request handler");
}
</script>
This is my simple attempt to retrieve the postback element, triggered from my UpdatePanel. My update panel looks like this:
<asp:UpdatePanel ID="UpdatePanel_Project" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList_Project" runat="server">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList_Customer" />
</Triggers>
</asp:UpdatePanel>
I believe I have did everything correctly...
Any ideas?
You have to set the ClientIDMode property value of the control (the DropDownList_Customer drop down list in this case) to AutoID. Please view my reply here.
What is your postback trigger ? This control seems to be missing DropDownList_Customer
<asp:AsyncPostBackTrigger ControlID="DropDownList_Customer" />
I finally solved this pain, here's my solution.
Basically we just need to override Microsoft's _uniqueIDToClientID function so it doesn't ignore our Static client Ids on postback elements.
You'll just need to add the following code at the bottom of your page.
if (Sys.WebForms.PageRequestManager) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm._uniqueIDToClientID = function (uniqueID) {
var clientID = uniqueID.replace(/\$/g, "_");
if (document.getElementById(clientID)) {
return clientID;
}
var lastDollar = uniqueID.lastIndexOf("$");
if (lastDollar === -1) {
return clientID;
}
if (lastDollar+1 > uniqueID.length) {
return clientID;
}
var staticID = uniqueID.slice(lastDollar + 1);
return document.getElementById(staticID) ? staticID : clientID;
};
}
Now, get_postBackElement() in your BeginRequestHandler will no longer be undefined!
Just make sure our code is executed after Microsoft's MicrosoftAjaxWebForms.js because we are overriding its _uniqueIDToClientID function.
Note: My function always returns the default WebForms ClientID if the element exists on the page. Only if the element cannot be found on
the page, does it check to see if an element with a static ID exists
on the page. If it exists, the staticID is used, otherwise it
defaults back to the default WebForms ClientID.