PageMethods returning undefined result? - c#

I have a very simple call to a PageMethod. When I step through my PageMethod in my .cs file, the value looks as expected. However, on the client side I get an undefined result. Any ideas? This should be horribly simple.
Here is my js: (EnablePageMethods="true" in my ASPX page)
function test() {
alert(PageMethods.MyMethod("Joe Blow"));
}
And here is my C#:
public partial class test : System.Web.UI.Page
{
[WebMethod]
public static string MyMethod(string name)
{
return "Hello " + name;
}
}

Here is the answer on how to call PageMethods using MS Ajax. First make sure you have downloaded the latest Ajax library from the MS website.
<asp:ScriptManager ID="sm1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<input type="button" value="Greeting" onclick="greetings()" />
<script language="javascript" type="text/javascript">
function greetings() {
PageMethods.GreetingFromPage(function(response) {
alert(response);
});
}
</script>
[WebMethod]
public static string GreetingFromPage()
{
return "greeting from page";
}
That is pretty much it!

You've to pass in a callback function that would be executed on Success / Exception. So in this case, it would be something like this
PageMethods.MyMethod("Joe Blow", onSuccess, onError);
function onError(desc) {
}
function onSuccess(result) {
}
I would check the documentation for the exact usage.

Check out the following screencast. It explains how to call the PageMethods using JQuery:
http://www.highoncoding.com/Articles/430_Calling_Page_Methods_Using_JQuery_and_Returning_JSON_Result.aspx

This is a great and concrete article on the subject.
For me, the following code is working.
I have a page that processes an excel file asynchronously; while processing, the function EsperarFinDelCargue() polls a PageMethod called CargueFinalizo()
each second to see if processing has ended. When processing finishes, a redirection takes place.
OnCallFinalizoComplete is the callback function for the PageMethod invocation, so there is where you need to use the resulting object.
<script type="text/javascript">
function EsperarFinDelCargue()
{
PageMethods.CargueFinalizo(OnCallFinalizoComplete);
if($('#<%=this.hidCargueFinalizado.ClientID %>').val() == "SI")
{
document.location = "CargarPanelHCP.aspx";
}
else
{
var t=setTimeout("EsperarFinDelCargue()",1000);
}
}
function OnCallFinalizoComplete(result,contexto,CargueFinalizo)
{
$('#<%=this.hidCargueFinalizado.ClientID %>').val(result);
}
</script>
And here is the PageMethod code in the aspx:
[System.Web.Services.WebMethod]
public static string CargueFinalizo()
{
//Whatever you need
return HttpContext.Current.Session["ResultadoCarguePanel"] != null ? "SI" : "NO";
}

Try This it will work fine
<script type="text/javascript">
function Generate()
{
var result = PageMethods.GenerateOTP(your parameter, function (response)
{
alert(response);
});
}
</script>

Related

Can't Use PageMethod (ajax in C# .net)

I try to use PageMethod in asp.net.
First I add script Manager to my aspx page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
I wrote onClick method on JS:
function TryAJAX() {
PageMethods.TryA( onSucess, onError);
function onSucess(result) {
alert('good.');
}
function onError(result) {
alert('Something wrong.');
}
}
and in the code behind:
[WebMethod]
public static String TryA()
{
return "JSON CHECK";
}
and I always get the message 'something wrong' . althouth that in debugger I see it's enter to the methood 'TryA'.
What is the problem?
thanks!!
i know this is not the exact path you were looking to take for a solution, but I think it is a WAY better option, so here's my 2 cents...
your button in html
<input type="button" id="myStupidButton" value="Click Me Yo" />
you javascript- I am going to use jQuery too , if that is really a problem I can give you a pure js option:
<script>
$(function(){
$(document).on('click', '#myStupidButton', function(){
$.ajax({
type: "POST",
url: "Mypage.aspx/TryA",
success: function(data){
// parse asp.net's response
data = $.parseJson(data);
//asp.net wraps all json into json like this "d" : "yourresponse"
alert(data.d);
}
});
});

MVC call method on click with / without postback

I have a question regarding the calling method from view.
Basically on my view I have 2 links:
1 link : When I click on it, some method should be called and executed, but nothing should change on webpage, so no postback.
2 link: When I click on it, some method should happen and postback can happen, on the same page
In controller I have:
public ActionResult FirstMethod(){ return View();}
public ActionResult SecondMethod(){ return View();}
In view:
#Html.ActionLink("Action 1", "FirstMethod", "Controller");
#Html.ActionLink("Action 2", "SecondMethod", "Controller");
So when I click on both action happens but then i get an error saying cannot find FirstMethod.chtml ..
So is this possible to have one method with postback and another one without? And how to return to the same page ... and not try to get FirstMethod.chtml ..
Following solution is based on AJAX -
Controller -
public class DemoController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult CallMe()
{
return new ContentResult() { Content = "This is Demo " };
}
}
Index.cshtml -
<h2>Index</h2>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#Click").click(function () {
$.ajax({
url: "/Demo/CallMe",
type: "GET",
error: function (response) {
alert(response);
},
success: function (response) {
alert(response);
}
});
});
})
</script>
<input type="button" value="Click" id="Click" />
First navigate to /demo/Index, that will display the page with above markup with a button in the page. And when we click on the Click button, we have -
The #Html.ActionLink method basically just forwards you to the specified controller-action, you cannot change this, since this is the purpose of the method.
You have to handle the click client-side, and bind a specific action to it (post some data to a url, and do nothing afterwards). One fairly easy way to do this, is to use jQuery.Post
Example from the above jquery link.
Example: Request the test.php page, but ignore the return results.
$.post("test.php");
Actually, there is no postback concept in asp.net mvc. all interactions with server should via the controller/action.
#Html.ActionLink() method just generate a link(tag a in html) and do nothing. everything happens after you send a request(such as click the link) to controller/action, if you want do nothing when click the link, you'd better use AJAX method like this
#Html.ActionLink("Action 1", "FirstMethod", "Controller", null/*routeValues*/, new { id = "link1Id" });
<script type="text/javascript">
$(function () {
$("#link1Id").click(function () {
$.get("/Contoller/FirstMethod", function () {
//do nothing or alert(something)
});
return false;
});
})
</script>
You can simply return another view after you've done what you wanted in your controller action:
public ActionResult SecondMethod()
{
//do something
return View("FirstMethod");
}
After you've seen this you will most probably be disgusted by the use of magic strings to reference views or controllers and that disgust is completely understandable :)
Then you should look whether something like T4MVC could fit your needs.

After form completion redirect to temporary view, then redirect to another

I've got a simple controller:
//Begin MakeBooking
public ActionResult MakeBooking()
{
return View(new Appointment() { Date = DateTime.Now });
}
[HttpPost]
public ActionResult MakeBooking(Appointment appt)
{
//repository stuff
return View("Completed",appt);
}
//End MakeBooking
public ActionResult Index()
{
return View();
}
I'm looking for an idiomatic way to show the user the Completed view once the form has been posted, say for five seconds, and then redirect back to, say, Index/Home. Does .NET provide any native way to do this?
Does .NET provide any native way to do this?
No, But you can certainly achieve your requirement using jQuery setTimeOut function. As an example please find below script -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
setTimeout(function () {
window.location.href = "#Url.Action("SubmitTag")"
}, 5000);
});
</script>
Above script will make the browser request to SubmitTag action. 5000 is the wait time in milliseconds before which the URL change code will fire.
You need to have this kind of script on your Completed view.

how to call C#(aspx.cs) function by using java script/Jquery by passing parameters

.aspx
-----------------------
<head>
<script type="text/javascript">
>> $(document).ready(function () {
$(".cssBtns").click(function () {
// call aspx.cs method generateInfo(this.id,this.className)
});
});
</script>
</head>
<body>
</body>
.aspx.cs
-----------------------
public void generateInfo(int btnId, string className){
print:// css button id:---
css button class:----
}
how can i call generateInfo method which is aspx.cs page by using java script/JQuery. and which is the best way.
You can use $.ajax(), $.post(), $.get() or $.getJSON() for doing this.
$(".cssBtns").click(function () {
$.ajax({
url : 'aspx function path here'
});
});
See the link below for more reference.
how to call an ASP.NET c# method using javascript
http://api.jquery.com/jQuery.ajax/

How to call C# method in javascript by using GeckoFX as the wrapper of XULRunner

I am using GeckoFX16 and xulrunner-16.0.2.en-US.win32 in my project.
The thing is, I want to call a C# method in javascript.
I am curious, is there a way to do this?
Just like below:
C# part:
private GeckoWebBrowser weBrowser;
public browser()
{
InitializeComponent();
Gecko.Xpcom.Initialize("xulrunner");
weBrowser = new GeckoWebBrowser();
weBrowser.Parent = this;
weBrowser.Dock = DockStyle.Fill;
weBrowser.Navigate("test.html");
}
public string loadData(){
//load data from local file.
return str;
}
javascript part:
<script type='text/javascript'>
var data = window.loadData();
alert(data);
</script>
I am new in this area, I’ll appreciate if it is possible!
Important update:
Currently code with event.initMessageEvent does not work because this construction has been replaced on
var event = new MessageEvent('yourEventName', { 'view': window, 'bubbles': false, 'cancelable': false, 'data': 'some data' });
You can use a MessageEvent to invoke code in c#, but as far as I know you can't then return a string like you're wanting to. One of the unit tests demonstrates how to invoke the c# code:
[Test]
public void AddEventListener_JScriptFiresEvent_ListenerIsCalledWithMessage()
{
string payload = null;
browser.AddMessageEventListener("callMe", ((string p) => payload = p));
browser.LoadHtml(
#"<!DOCTYPE html>
<html><head>
<script type='text/javascript'>
window.onload= function() {
event = document.createEvent('MessageEvent');
var origin = window.location.protocol + '//' + window.location.host;
event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null);
document.dispatchEvent (event);
}
</script>
</head><body></body></html>");
browser.NavigateFinishedNotifier.BlockUntilNavigationFinished();
Assert.AreEqual("some data", payload);
}
I know it's awkward, but you could then use a c#-->javascript call to get data back to javascript-land. See This Question for how to do that. So your javascript would first send this message to c# land, then it would get a callback with the string value you need.
Hope that helps.
You can add message event listener to your web browser and call your method like this:
private void load()
{
browser.AddMessageEventListener("myFunction", ((string s) => this.showMessage(s)));
browser.LoadHtml
(
#"<!DOCTYPE html>
<html><head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">
<script type=""text/javascript"">
function fireEvent(name, data)
{
event = document.createEvent('MessageEvent');
event.initMessageEvent(name, false, false, data, null, null, null, null);
document.dispatchEvent(event);
}
</script>
</head>
<body>
<input type=""button"" onclick=""fireEvent('myFunction', 'some data');"" value=""SHOW DATA"" />
</body></html>"
);
}
...
private void showMessage(string s)
{
MessageBox.Show(s);
}
Now you can add more msg events to your msg listener (if you need to) and fire them all in the same way.

Categories

Resources