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
Related
I need a ASP.net application which is only kind of "pageDisplayer" from content which is coming from an API. So I choose ASP.net Webform and tried the following:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PMLetterAcceptance.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:Literal runat="server" id="JavaScript"></asp:Literal>
</head>
<body>
<form id="letterform" runat="server">
<div>
<%= pageContent %>
</div>
</form>
</body>
public partial class WebForm1 : System.Web.UI.Page
{
protected string pageContent = "";
protected void Page_Load(object sender, EventArgs e)
{
...// here I fetch the html and javascript content from the API
dynamic json = Json.Decode(streamReader.ReadToEnd());
if (json.status != "OK")
pageContent = json.error;
else
pageContent = json.html;
JavaScript.Text = json.script;
}
}
The html content and the script are loaded correct but I cannot access DOM elements in the javascript. The javascript looks like that
(function()
{
function processForm(e)
{
... // Here I want to do some stuff before sending the form
}
let form = document.getElementById('letterform');
if (form.attachEvent)
form.attachEvent("submit", processForm);
else
form.addEventListener("submit", processForm);
})();
No I get the error "form is null". For me it looks like the javascript is executed before the DOM is ready. But how can I change this to make it work like expected?
Try putting the JS (literal) at the bottom of the page, before the closing body tag. That way, the HTML will be loaded before the JS tries to find elements.
I want to read the Page(.aspx) Hiddenfield Value in the User Control that is placed on that Page and process some logic.
FOr eg: I have a hidden field x on a Page. The Page has many user controls and I want to access this hidden field (x) in those User Controls where value of x will be set by a Javascript in the Page.
I am trying to find the HiddenControl and read its value from codebehind of usercontrol(.ascx.cs) but always get null.
HiddenField colname = UIUtils.FindControlRecursive(this.Parent.Page, "MainContent_AssignedTo_ColName") as HiddenField;
The ID is same as the hiddenfield on client Side. I tried this.Parent and this.Parent.Parent for the first argument too but no luck.
what am I missing here.
Here is my aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestFindControl._Default" %>
<%# Register Src="ReadHiddenField.ascx" TagName="Assign" TagPrefix="uc1" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="HiddenField1" runat="server" Value="10">
</asp:HiddenField>
<asp:placeholder ID="Placeholder1" runat="server"><uc1:Assign id="test" runat="server"></uc1:Assign> </asp:placeholder>
</div>
</form>
</body>
</html>
and here is my code behind on control:
protected void Page_Load(object sender, EventArgs e)
{
HiddenField test = (HiddenField)Page.FindControl("HiddenField1");
var j = test.Value;
}
Try:
HiddenField colname = (HiddenField)Page.FindControl("The id of control");
private void GetParentPageHiddenField()
{
System.Web.UI.WebControls.HiddenField ParenthiddenField = null;
Control ctl = this.Parent;
while (true)
{
ParenthiddenField = (System.Web.UI.WebControls.HiddenField)ctl.FindControl("ParentPageHiddenFieldID");
if (ParenthiddenField == null)
{
if (ctl.Parent == null)
{
return;
}
ctl = ctl.Parent;
continue;
}
break;
}
var parentHiddenFieldValue=ParenthiddenField.Value;
}
Please help me to refresh periodically an image in a web form (asp.net).
Here is my code. The image is not refreshing. Thank you in advance.
<!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" src="Scripts/jquery-1.11.0.min.js">
$(document).ready(function () {
var refreshId = setInterval(function () {
var obj = document.getElementById("<%=Image1.ClientID%>");
var src = obj.src;
var pos = src.indexOf("?");
if (pos >= 0) {
scr = src.substr(0, pos);
}
var date = new Date();
obj.src = src + '?v=' + date.getTime();
return true;
}, 10000);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/sOverview.png" />
</div>
</form>
</body>
</html>
and the code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Image1.ImageUrl = Image1.ImageUrl + "?" + DateTime.Now.ToLongTimeString()
End Sub
A script element gets its script from either the text node inside it, or the URL of the src attribute. Not both.
If you want to load two scripts (one from a URL and on in the text node) then you need two script elements.
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.
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.