Load a javascript function while page loads - javascript

Hi
I want to run a javascript function when the page loads. But as my page derives from the master page there is no form . The is my aspx file
<%# Page Title="" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeFile="test3.aspx.vb" Inherits="test3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
<script language="javascript">
var m_Names = new Array();
function LoadArray() {
PageMethods.Load_Array(onSucceeded, onFailed);
}
function onSucceeded(result, userContext, methodName) {
m_Names = result;
}
function onFailed(error, userContext, methodName) {
alert("An error occurred")
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<asp:TextBox ID="txt_model_code" runat="server"></asp:TextBox><br />
<br />
<input type="button" value="db Function" /><br />
</asp:Content>
I want to run the LoadArray() function initialy when the page loads. This function is calling a pagemethod given in aspx.vb code file..
Partial Class test3
Inherits System.Web.UI.Page
<System.Web.Services.WebMethod()>
Public Shared Function Load_Array() As String()
Dim Model_Name_old As String()()
Dim mod_code As String()
Dim mod_name As String()
Dim cod_upper As Integer
//calling webservice that retunrs a jagged array
Dim ins As New localhost_insert_model.dbModel
Model_Name_old = ins.get_Model_Name("A")
mod_code = Model_Name_old(0)
mod_name = Model_Name_old(1)
Return mod_name
End Function
End Class
So how can i load the javascrip LoadArray() function onPageLoad in this scenario??

This one should work
<script language="javascript">
var m_Names = new Array();
window.onload = function ()
{
LoadArray();
}
.....your functions
</script>

I think you can use $document.ready() from jQuery.

If you don't need the whole page to have loaded completely you could just call it after you created the functions?
var m_Names = new Array();
function loadArray() {
PageMethods.Load_Array(onSucceeded, onFailed);
}
function onSucceeded(result, userContext, methodName) {
m_Names = result;
}
function onFailed(error, userContext, methodName) {
alert("An error occurred")
}
loadArray();

You can use this code:
Sys.Application.add_load(function(e) { LoadArray(); });
Is its name suggest, this is a page_load handler, which pretty much duplicates in functionality is server-side counter part.

Related

Invoking a C# Function that doesn't return anything from JavaScript

Consider the following codes:
In my .ascx
<a id="1" onclick="registerLastViewed(this.id);">Example</a>
<asp:HiddenField id="hdID" runat="server" />
<script type="text/javascript>
function registerLastViewed(ID) {
document.getElementById('<%= hdID.ClientID %>').value = ID;
"<%= RegisterLastViewed() %>"; //dies here
}
</script>
In my .ascx.cs
public void RegisterLastViewed()
{
//todo required logic
}
Basically what I plan to do is:
Clicking on <a> will call the Javascript function which will invoke my C# function from code behind.
But everytime I try to get into this page, it dies. Redirect loops and dies.
Is there a way to do this without using webmethod?
for reference, this runs fine:
<script type="text/javascript">
var usr = "<%=getUserId() %>";
</script>
public string getUserId() {
string userId = "";
if (Session[PropertiesKey.SessionKeys.UserObjLoginUser] != null)
{
UserMaster loginUser = (UserMaster)Session[PropertiesKey.SessionKeys.UserObjLoginUser];
userId = loginUser.UserID;
}
return userId;
}

`getJSON()` of jQuery not calling same page's function to get JSON data

I want to use getJSON()'s demo to show its use insetead of $.ajax.
I've till created the following code.
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Test_JSON.aspx.vb" Inherits="Test_HTML" %>
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test HTML</title>
<script src="Script/jquery-1.9.1.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter Name:
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnView" Text="View Label of Name" />
</div>
</form>
<script type="text/javascript">
function getJsonData() {
debugger;
$("#btnView").val = $("#txtName").val();
var objJson = {};
objJson["name"] = $("#txtName").val();
return objJson;
}
$("#btnView").click(function(event) {
debugger;
$.getJSON('/Test_JSON.aspx/getJsonData', function(result) {
debugger;
$('<p> APPEND TEXT </p>').appendTo('#btnView');
$('<p> PREPEND TEXT </p>').prependTo('#btnView');
});
});
</script>
</body>
</html>
VB code for PageMethod
Imports Newtonsoft.Json
Partial Class Test_HTML
Inherits System.Web.UI.Page
<Web.Services.WebMethod()> _
Public Shared Function getJsonData(ByVal name As String) As String
Dim jsonString As String = String.Empty
Dim dt_jsonData As New DataTable
Dim dr As DataRow = dt_jsonData.NewRow
Try
dt_jsonData.Columns.Add("name")
dr("name") = name.ToString.Trim()
dt_jsonData.Rows.Add(dr)
If dt_jsonData.Rows.Count <> 0 Then
jsonString = JsonConvert.SerializeObject(dt_jsonData)
End If
Catch ex As Exception
Return ""
Exit Function
End Try
Return jsonString
End Function
End Class
I want to get data from getJsonData(). But my getJSON() is not getting executed with URL. Is there any other way I should use this?
All I need to do is:
1> Enter text in text box
2> Click on button
3> Get textbox's value through getJSON() method and use it somewhere else.
4> And also use appendTo and prependTo methods for demo.

ASP.NET Call Code Behind Function From Javascript

I made a webmethod that I'm trying to call from javascript, but it doesn't seem to be firing. I'm grabbing the selected index value from a listbox inside of a usercontrol and passing it to my webmethod to delete the selected user. I've looked at countless sites and haven't found a solution. I'm not getting any errors, everything else seems to be working. I've tried calling this function from a public sub in the code behind also with no luck. Any suggestions are greatly appreciated!
<%# Page Language="VB" AutoEventWireup="false" ClientIDMode="Static" CodeFile="Edit.aspx.vb" Inherits="_Default" %><%# Register src="AdminEdit.ascx" tagname="AdminEdit" tagprefix="uc1" %>
<%# Register TagPrefix="asp" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3
.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function YesNo() {
var result = confirm("Are you sure you want to delete?");
if (result == true) {
//var strUser = e.options[e.selectedIndex].value;
var e = document.getElementById('<%= newLb.clientID %>');
//var e = document.getElementById("ListBox1");
var si = e.selectedIndex;
var sv = e.value;
document.write("TRUEEEEE");
PageMethods.DeleteUser(sv);
}
else {
document.write("FALSEEEEEE");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="A1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Login.aspx">Login</asp:HyperLink>
</div>
<asp:HyperLink ID="HyperLink2" runat="server"
NavigateUrl="~/ChangePassword.aspx">Change Password</asp:HyperLink>
<br />
<asp:HyperLink ID="HyperLink3" runat="server" NavigateUrl="~/CreateUser.aspx">Create User</asp:HyperLink>
<br />
<asp:HyperLink ID="HyperLink4" runat="server" NavigateUrl="~/AddRole.aspx">Add Roles</asp:HyperLink>
<br />
<br />
<uc1:AdminEdit ID="AdminEdit1" runat="server" />
</form>
</body>
</html>
Public newLb As New ListBox
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Roles.IsUserInRole("admin") Then
ElseIf Roles.IsUserInRole("editor") Then
newLb = CType(AdminEdit1.FindControl("ListBox1"), ListBox)
End If
End Sub
<System.Web.Services.WebMethod()>
Public Shared Function DeleteUser(ByVal uName As String) As String
Dim u As MembershipUser
Dim newEdit As New _Default
Dim _newLb = newEdit.newLb
_newLb.Items.RemoveAt(0)
u = Membership.GetUser(uName)
Try
Membership.DeleteUser(u.UserName)
Catch ex As Exception
Return "Error:" & ex.Message
End Try
Return u.IsApproved.ToString
End Function
I think you should use JSon to call the web method, here are simple example
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "yourpage.aspx/yourmethod",
data: "{}",
dataType: "json",
success: function(data) {
//Write functionality to display data
},
error: function(result) {
alert("Error");
}
});
And here is the link that may help you Link

get_postBackElement() is always undefined

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

Using ASP.NET Variable in Javascript inside UpdatePanel

I have a javascript function inside UpdatePanel. The variable should be updated on UpdatePanel partial postback.
Using the below code, the javascript variable jsonStringASPX will always have the initial value, regardless of what JsonString ASP.NET variable has.
<script type="text/javascript">
function pageLoad(){
LoadExpenseList();
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<script type="text/javascript">
function LoadExpenseList() {
var jsonStringASPX = <%= JsonString %>;
var jsonHeaderStringASPX = <%= JsonHeaderString %>;
//Works with the Strings
}
</script>
</ContentTemplate>
</asp:UpdatePanel>

Categories