Trouble calling C# Method from javascript - c#

I read some forums and found an easier way to call a C# Method from JavaScript but it's not working. I did it in my live app and it didn't work so I took a fresh project and used the code as below:
ASPX Mark-up
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:Button ID="btnMe" runat="server" OnClientClick="jsfun()" />
</div>
</form>
</body>
</html>
Javascript
<script type="text/javascript">
function jdfun() {
PageMethods.CSFun(onSucess, onError);
}
function onSucess(result) {
alert(result);
}
function onSucess(result) {
alert(result);
}
</script>
C#
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string CSFun()
{
string result = "Hey Yeah";
return result;
}
}
No Error No Exception. The Debugger is not even going into the C# code.
Can anyone help me out.
Thanks.

Edit
I didn't really know about this, but I read a little and fixed your code.
Here is the code that works:
js:
<script type="text/javascript">
function jsfun() {
PageMethods.CSFun(onSuccess, onError);
}
function onSuccess(result) {
alert(result);
}
function onError(result) {
alert(result);
}
</script>
aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:Button ID="Button1" runat="server" OnClientClick="jsfun()" />
</div>
</form>
</body>
</html>

Basic Example to do the same
aspx page
<form runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
<fieldset id="ContactFieldset">
<label>
Your Name
<input type="text" id="NameTextBox" /></label>
<label>
Email Address
<input type="text" id="EmailTextBox" /></label>
<label>
Your Message
<textarea id="MessageTextBox"></textarea></label>
<button onclick="SendForm();">
Send</button>
</fieldset>
</form>
Page Method (.cs)
using System;
using System.Web.Services;
public partial class ContactUs : System.Web.UI.Page
{
[WebMethod]
public static void SendForm(string name, string email, string message)
{
if (string.IsNullOrEmpty(name))
{
throw new Exception("You must supply a name.");
}
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
if (string.IsNullOrEmpty(message))
{
throw new Exception("Please provide a message to send.");
}
// If we get this far we know that they entered enough data, so
// here is where you would send the email or whatever you wanted
// to do :)
}
}
javascript function
function SendForm() {
var name = $get("NameTextBox").value;
var email = $get("EmailTextBox").value;
var message = $get("MessageTextBox").value;
PageMethods.SendForm(name, email, message,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
// Dispaly "thank you."
$get("ContactFieldset").innerHTML = "<p>Thank you!</p>";
}
function OnFailed(error) {
// Alert user to the error.
alert(error.get_message());
}

Related

How to get a URL file name without extension in a webmethod

I have this URL (mydomain.com/mypage.aspx). I want to get the file name "mypage" only in a webmethod. I tried the following code but I only get the name of the function itself (MyMethod). I don't get the name of the page from the URL. Any help is well appreciated.
EDIT
To be more specific the webmethod resides in a user control so using FilePath OR PhysicalPath would give me the name of the UserControl file name (MyUserControl) and not the aspx page (mypage) in the URL.
mypage.aspx
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
<uc:myUserControl runat="server" />
</asp:content>
myUserControl.cs
public static string PageName { get {
return (string)(Path.GetFileNameWithoutExtension(
Convert.ToString(HttpContext.Current.Request.Url)));
} }
OR
public static string PageName { get {
return (string)(Path.GetFileNameWithoutExtension(
HttpContext.Current.Request.RawUrl));
} }
OR
public static string PageName { get {
return (string)(Path.GetFileNameWithoutExtension(
HttpContext.Current.Request.PhysicalPath));
} }
[WebMethod]
public static string MyMethod()
{
StringBuilder SBstring = new StringBuilder();
SBstring.Append(PageName);
return SBstring.ToString();
}
Just use FilePath like this:
var fi = new FileInfo(HttpContext.Current.Request.FilePath);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fi.Name);
Complete working solution for required structure (Master Page -> Content Page -> User Control
Site Master
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebTester.Site1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Webform1.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebTester.WebForm1" %>
<%# Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
</asp:Content>
Webform1.aspx.cs:
namespace WebTester
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string ProcessIT(string name, string address)
{
return WebUserControl1.ProcessIT(name, address);
}
}
}
WebUserControl1.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebTester.WebUserControl1" %>
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something is wrong.');
}
}
</script>
<div>
<p>Please enter data:</p>
Name<br />
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
Address<br />
<asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
</div>
WebUserControl1.ascx.cs:
namespace WebTester
{
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public static string ProcessIT(string name, string address)
{
var fi = new FileInfo(HttpContext.Current.Request.FilePath);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fi.Name);
string result = string.Format("Name '{0}' and address '{1}' came from Page '{2}'", name, address, fileNameWithoutExtension);
return result;
}
}
}

I need a textbox value in form 1 to be inserted into form2 as a string in the html level in asp

I would like to 'transfer' a textbox value into a html code. E.g the textbox value is a website like http://www.google.com in form1.aspx. and i would like the value to be put into the html code in form2.aspx . Might i ask how i should be going around on this?
<span class="logoposition">
<img src="Logo.jpg" height= "120"; width="280"; />
</span>
Like i would like the textbox1 value to replace the current www.google.com
Here's how you can do this:
Webform1 Markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SOTest1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Your text: ">
</asp:Label><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="GO" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
Webform1 Code:
using System;
namespace SOTest1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string myString = Server.HtmlEncode(TextBox1.Text);
Response.Redirect("Webform2.aspx?mystring=" + myString);
}
}
}
Webform2 Markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="SOTest1.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<span class="logoposition">
<img src="Logo.jpg" height= "120"; width="280"; />
</span>
</div>
</form>
</body>
</html>
Webform2 Code:
using System;
namespace SOTest1
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string mystring = Request.QueryString["mystring"];
myAnchor.HRef = mystring;
myAnchor.InnerText = mystring;
}
}
}

modal dialog not close

RegistrationPage.aspx
function btnSearchClick()
{
if (window.showModalDialog)
{
window.showModalDialog(
"Search.aspx",
"Search Patient",
"dialogWidth:800px; dialogHeight:400px"
);
return false;
}
}
Search.aspx
$(document).ready(function ()
{
$("input[id$='btnAdd']").live('click', function (e) {
hidID.value = $.trim($('table td.csstablelisttdselected:first').text());
return true;
});
});
Seach.aspx.cs
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Redirect("RegistrationPage.aspx?ID=" + hidID.Value, true);
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"CloseScript",
"window.close()",
true
);
}
In RegistrationPage.aspx page on click of button search pop up dialog box.
In Search page i am getting id in hiddenfield and redirect to registration page.
When I click on btn add then dialog not close and it redirect to registration page within dialog.
Please dont give answer like "use jquery dialog box","or use another dialog control"
This is a tested example :
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
function btnSearchClick()
{
window.returnValue = undefined;
var result = window.showModalDialog("Search.aspx", window, "dialogHeight:650px; dialogWidth:900px;");
if (result == undefined)
result = window.returnValue;
if (result != null && result != "undefined")
alert(result);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="btnOpen" onclick="btnSearchClick();" />
</div>
</form>
</body>
</html>
Search.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script>
function CloseModal() {
if (window.opener) {
window.opener.returnValue = 'your return value';
}
window.returnValue = 'your return value';
self.close();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
Search.aspx.cs
using System;
using System.Web;
using System.Web.UI;
public partial class Search : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "CloseScript", "closescript()", true);
}
}
So instead of redirect your user you could pass a value from Modal to Opener.
Here another example : Modal Dialog ReturnValue
Hope can help.

Affect another document on submit

I've got a upload function that pops up in a diffrent window, when i've submitted i want to send infomation back to the page that the upload window opened from.
Is that possible some way with ASP.net or C#?
Or would i have to use some javascript ? and how?
My 2 pages:
news.aspx - Contains a formview with my news. and a form with some inputs in.
This is where the link to open the upload page is...
uploader.aspx - Contains my upload controller and C# code to upload.
This should send a string from my C# code back to news.aspx and put it in one of my input fields or a label, not important.
uploader.aspx file:
<form id="form1" runat="server">
<div>
Vælg en fil at uploade:<br />
<asp:FileUpLoad id="FileUpLoad1" runat="server" />
<asp:Button id="UploadBtn" Text="Upload File" OnClick="UploadBtn_Click" runat="server" Width="105px" />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
Behind Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class admin_Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadBtn_Click(object sender, EventArgs e) {
Label1.Text = "Status: Uploader...";
if (FileUpLoad1.HasFile) {
FileUpLoad1.SaveAs(#"C:\Users\138409\Documents\Visual Studio 2010\Projects\Musicon\img\news\" + FileUpLoad1.FileName);
Label1.Text = "Status: " + FileUpLoad1.FileName + " er blevet uploadet";
} else {
Label1.Text = "Status: Filen blev ikke uploadet...";
}
}
}
Here is some Javascript code to create a popup window and, before the popup window closes, retrieve some information. (I will add a jQuery example in a bit)
//Site1.Master
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="PopupRedirect.Site1" %>
<!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>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
//Page1.aspx
<%# Page Title="" Language="C#" MasterPageFile="Site1.Master" AutoEventWireup="true" CodeBehind="Page1.aspx.cs" Inherits="PopupRedirect.Page1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript">
var message = "Hello World!";
var closeWindow = function(event) {
event.preventDefault();
window.close();
};
window.onload = function() {
document.getElementById('upload').addEventListener('click', closeWindow, false);
};
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<button id="upload">Upload File</button>
</asp:Content>
//UploadPage.aspx
<%# Page Title="" Language="C#" MasterPageFile="Site1.Master" AutoEventWireup="true" CodeBehind="UploadPage.aspx.cs" Inherits="PopupRedirect.UploadPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript">
var popupWindow;
var windowOptions = "menubar=yes,location=yes,resizable=no,scrollbars=no,status=yes,width=350,height=350";
var upload = function (event) {
event.preventDefault();
popupWindow = window.open("Page1.aspx", "Upload Page", windowOptions);
popupWindow.onbeforeunload = pageClose;
};
var pageLoad = function(event) {
document.getElementById('uploadLink').addEventListener('click', upload, false);
};
var pageClose = function (event) {
//put the code here that you want to execute when the window is done.
//like getting the value of some javascript variables
if(typeof (popupWindow.message) != "undefined") {
alert(popupWindow.message);
}
};
window.onload = pageLoad;
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<span>Welcome to this page! Click to upload.</span>
<button id="uploadLink">Upload</button>
</asp:Content>

passing value from ASP.NET to Java Scripts to HTML

I need value to be passing from ASP.NET page to JavaScript and then to HTML textfield.
My following code is able to read values from ASP.NET to JavaScript but unable to pass value form JavaScript to HTML TextField. Can anybody please correct my code.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
function can() {
var myVariable = '<%=ServerSideVariable %>';
document.write(myVariable);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<br />
<br />
<br />
<br />
<input id="Text1" type="text" value='can()'/>
</div>
</form>
</body>
</html>
Default.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 _Default : System.Web.UI.Page
{
public string ServerSideVariable { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
string pval = "Passed value;
ServerSideVariable = pval;
}
}
document.getElementById('Text1').value = myVariable;
But you need to move the assignment script block bellow the declaration of element Text1, or do it on document.ready
Anyway, you also need to error check.
It's best to use JQuery anyway, and get familiar with it.
As others have said with javascript OR like this:
(since there is nothing in your example that requires javascript -- KISS-- don't use javascript if you don't have to do so.)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<br />
<br />
<br />
<br />
<input id="Text1" type="text" ><%=ServerSideVariable %></input>
</div>
</form>
</body>
</html>
Do this instead in a document.load.
document.getElementByID('Text1').value = myVariable;

Categories

Resources