ScriptManager.RegisterStartupScript() method not working - ASP.NET, C# - javascript

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);
}

Related

How can i do database CRUD operations by taking parameters from aspx.cs file?

<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>

Calling onclickserver in html it doesn't fire any event

I'm facing a problem. When calling an html input tag on C# it doesn't fire any event. Can you please give an advice on the below html code and c# code?
<input type="submit" id="btnBeforeOk" runat="server" name="btnBeforeOk" value="Login" onserverclick="BtnBeforeOk_ServerClick" />
protected void BtnBeforeOk_ServerClick(object sender, EventArgs e)
{
Label1.Text = "Youhana";
}
}
Have you tried with your button code like this:
<script language="C#" runat="server">
protected void BtnBeforeOk_ServerClick(object sender, EventArgs e) {
....
}
</script>

Parse 2D array from ASP.NET C# code behind to Javascript

I've written a function (addCalendarEvents) which takes in an array (events) and parses into a custom calendar. Everything works perfectly fine when its fired through the document.ready function, events are registering and etc.
Javascript
$(document).ready(function () {
loadCalendar(null);
addCalendarEvents([{ title: 'All Day Event', start: '2016-01-01' }, { title: 'Long Events', start: '2016-01-07', end: '2016-01-10' }]);
});
function addCalendarEvents(events) {
$('#calendar').fullCalendar('addEventSource', events)
}
However, I also need them to be fired through the code behind to add events dynamically. I've tried using ScriptManager's RegisterStartupScript, but it's not working. Is there a proper way for me to do so?
C# Code Behind
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "addEvents", "addCalendarEvents([{ title: 'Other Event', start: '2016-01-01' }, { title: 'Other Long Events', start: '2016-01-07', end: '2016-01-10' }]);", true);
}
It might be simpler to use a <asp:Literal id="StartupScript" runat=server /> control containing the $(document).ready() function to inject your page load callouts.
You could write the statements to the literal control within your Page_Load event and they should get executed by the client when the page is ready.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<asp:Literal ID="CodeInject" runat="server"/>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
And the code behind is:
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder SB = new StringBuilder();
SB.Append("<script>");
SB.Append("$(document).ready(function () {");
// statements here
SB.Append("alert('test');");
SB.Append("});</script>");
CodeInject.Text = SB.ToString();
}
try to convert the data into json while adding the script. Add your assemblies
using this Assembly
using System.Web.Script.Serialization;
Then Deserialize your object
var json = new JavaScriptSerializer().Serialize(obj);
then call registerStartupScript
ScriptManager.RegisterStartupScript(this, this.GetType(), "addEvents", json, true);
and at client side do this to convert it into json
var obj = JSON.parse(string);

Calling the button.click() event from javascript doesn't fire

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;"

Set focus on an asp.net control on Page Load

I want to set focus on a control when page is loaded.
I wrote this code but not working..
protected void setFocus(System.Web.UI.Control ctrl)
{
string s = "<SCRIPT language='javascript'>document.getElementById('" + ctrl.ID + "').focus() </SCRIPT>";
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "focus", s);
}
and this line in PageLoad method:
this.setFocus(txtHeightfeet);
Please help.
EDIT:
This is HTML:
<input name="ctl00$MainContent$txtHeightfeet" type="text" maxlength="2" id="MainContent_txtHeightfeet" class="textEntry2" style="width:65px;" />
This is aspx code:
<asp:TextBox ID="txtHeightfeet" runat="server" CssClass="textEntry2" MaxLength="2" Width="65"></asp:TextBox> ft
and in code behind cs file, i declared it the same as you have mentioned.
You should be able to just call the Focus() method of the control.
No need for that Javascript.
protected void Page_Load(object sender, EventArgs e)
{
txtHeightfeet.Focus();
}

Categories