Trying to invoke this web service using AJAX...
The web service is as follows
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public String countryCode(String input)
{
StringBuilder strings = new StringBuilder("", 10000);
String text = System.IO.File.ReadAllText(Server.MapPath("countryCodes.txt"));
String[] countries = Regex.Split(text, "#");
var valids = new List<String>();
foreach (String c in countries)
{
if (c.ToUpper().StartsWith(input.ToUpper()) || c.ToLower().StartsWith(input.ToLower()))
{
if (input == "")
{
break;
}
valids.Add(c);
}
}
return (valids.Any()) ? String.Join(" ", valids) : "No results found for your input!";
}
}
I have set up an empty web form and called the service reference in the script manager like so
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService1.asmx" />
</Services>
</asp:ScriptManager>
And I have my javascript as follows below
<script type= "text/javascript">
var a = wRequest.set_userContext("user's context");
var onClick = function () {
CountryCodes.WebService1.countryCode($get("TextBox1"), onSucess, onFailed);
}
var onSuccess = function (result) {
$get("Label3").innerHTML = result;
}
var onFailed = function (result) {
$get("Label3").innerHTML = "No results found for your input!";
}
</script>
Now my understanding is that when the button is pressed it will take the input of TextBox1's value and use it as the argument for my WebService.countryCode method and therefore if it succeeds it will set label 3 to the result of the method and if it doesn't succeed it will set label 3 to the string provided...
This however does not happen.... Infact nothing happens when I click my button, for clarity, here is my button declaration...
<input type="button" value="Find Country Codes " onclick ="onClick()" />
This button is in the same place the automated textbox1 and label code is generated.
So my question is, what have I done wrong and how can it be fixed?
Any clarifications needed just post below thank you.
Regards
EDIT : yes I have commented out this line in the web service
"[System.Web.Script.Services.ScriptService]"
Decorate your web service class with [System.Web.Script.Services.ScriptService], like this:
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
This allows your web service to be called by your JavaScript.
Also, change your call to the web service to remove the CountryCodes prefix, like this:
var onClick = function () {
WebService1.countryCode($get("TextBox1"), onSucess, onFailed);
}
Related
I want to call a javascript and a function written in Model Class using a single button click. I used the following code:
<script language="javascript" type="text/javascript">
function RunEXE() {
var txtfile = document.getElementById("txtFileName");
//var txtProgram = document.getElementById("txtProgram");
//if ((!String.IsNullOrEmpty(txtfile)) && (!String.IsNullOrWhiteSpace(txtProgram))) {
if (txtfile.value != "") {
var oShell = new ActiveXObject("WScript.Shell");
//var prog = "c:\\Pgms\\sample0.exe";
var prog = "\\\\Test-PC\\Programms\\" + txtfile.value + ".exe";
oShell.Run('"' + prog + '"', 1);
} else {
alert('The file name must be entered in file name textbox');
}
}
</script>
<input type="submit" name="button" value="Run" onclick="RunEXE()" />
The below code is Model function:
public ActionResult Run(UserProgram userProgram)
{
SaveAndCompile(userProgram);
return null;
}
But its working with Run() alone and not running RunEXE()
[HttpPost]
public ActionResult RunAction(string option1)
{
//if needed, you can use the "option1" value to determine the UserProgram to pass
UserProgram userProgram = new UserProgram();
Run(userProgram);
//you can return a JSON reuslt that you can evaluate back at the client
return Json(new { #Success = true, #MyString = "a string" });
}
$.post('#Url.Action("RunAction", "MyController")',
{
option1: "some optional value"
},
function (data) {
alert("success!");
//here you have access to your JSON result via data, for example:
//data.Success = true
//data.MyString = "a string"
}
);
In your case, you can submit your form by JQuery submit function.
I assume your code will like below:
<form id="form" action="/Run">
// your some inputs
<input type="submit" name="button" value="Run" />
</form>
And the javascript for submitting will be:
$(function() {
$('#form').submit(function() {
// to do something before the form is submitted
RunEXE();
return true; // return false to cancel form action
});
});
Cheers.
I want to redirect to another page and pass some parameters only using javascript. I am not supposed to use query string. Is there any way to achieve this? I am working on asp.net.
I want this redirection to use with devexpress scheduler control where when a user clicks on an appointment, the user be redirected to another page by passing the selected appointment's ID as parameter. It should not be passed as query string.
I would also like to know how to retrieve such kind of invisible parameter from the redirected page.
Ok I found out my solution.
I used javascript to click a <asp:Button> that is set to style="display:none". In my scenario, I could get the properties of scheduler appointment that I had clicked. I then put these properties in hidden fields and in the server side click event of this 'invisible' button, I use these hidden field values to make my redirection through server side. My code is as below
<asp:Button ID="Appointment" runat="server" Text="sample"
onclick="Appointment_Click" style="display:none"/>
<asp:HiddenField ID="hfID" runat="server" />
<asp:HiddenField ID="hfSubject" runat="server" />
<asp:HiddenField ID="hfDate" runat="server" />
<script type="text/javascript" language="javascript">
function OnAppointmentClick(s, e) {
//debugger;
var apt = scheduler.GetAppointmentById(e.appointmentId);
var apt1 = scheduler.GetAppointmentProperties(e.appointmentId);
var aptID = document.getElementById('<%= hfID.ClientID %>');
var aptDate = document.getElementById('<%= hfDate.ClientID %>');
var aptSubject = document.getElementById('<%= hfSubject.ClientID %>');
aptID.value = e.appointmentId;
var date = (apt.startDate.getMonth()+1) + '/' + apt.startDate.getDate() + '/' + apt.startDate.getYear();
aptDate.value = date;
aptSubject.value = apt.CODE;
document.getElementById('<%= Appointment.ClientID %>').click();
}
</script>
Try this:
ASP.net Code:
Response.Headers.Add("id", "testtest");
Response.Redirect("http://www.somesite.com/somepage.aspx");
Java Script Code:
window.location = 'http://www.somesite.com/somepage.aspx?q=manvswild';
jQuery Code:
var url = "http://www.somesite.com/somepage.aspx?q=manvswild";
$(location).attr('href',url);
jQuery Ajax Code:
$.ajax({
type : 'POST',
url : 'page.aspx',
data : {
paramname1 : "put_param_value_here",
paramname2 : "put_param_value_here",
paramname3 : "put_param_value_here"
},
dataType : 'html',
success : function (e) {
window.location = e;
}
});
// or short method is
$.post("page.aspx", {
param1 : 'one',
param2 : 'two'
}, function (data) {
window.location = data;
});
jQuery plugin: http://plugins.jquery.com/project/query-object
alert($.query.set("section", 5).set("action", "do").toString());
Output:
?section=5&action=do
try this
document.location.href = "window-location.html"
already asked here
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.
I'm working on a website where the user should be able to fill out a dynamic expanding form.
I would add a row with greyed out fields and when the user gives focus to one of those field the following javascript would add the line
<tr class="unSelected">
<input name="id[]">
<input name="blabla[]">
</tr>
$('.unSelected').focusin(function () {
if ($(this).hasClass('unSelected')) {
var row = $(this).clone(true);
$(this).after(row);
$(this).removeClass('unSelected');
}
});
but how would one do this using razor and asp.net, as the objects wont be autogenerated then?
In ASP.NET MVC, if you have a model class like:
public class PageModel
{
public Collection<RowItem> RowItems { get; set; }
}
public class RowItem
{
public int Id {get;set;}
public string MoreFields { get; set; }
}
And your javascript adds rows like so:
<script type="text/javascript">
var currentRowIndex = 0;
$(document).ready(function () {
SetFocusEventForInputs('unSelected0');
});
function SetFocusEventForInputs(className) {
var inputSelector = '.' + className;
$(inputSelector).focusin(function () {
AddNewRowTo(this);
$(inputSelector).unbind('focusin').removeClass(className);
});
}
function AddNewRowTo(sendingInputField) {
currentRowIndex++;
var className = 'unSelected' + currentRowIndex;
var collectionNamePrefix = 'RowItems[' + currentRowIndex + '].';
var idField = $('<input/>').attr('name', collectionNamePrefix + 'Id').attr('type', 'text').attr('class', className);
var moreFields = $('<input/>').attr('name', collectionNamePrefix + 'MoreFields').attr('type', 'text').attr('class', className);
var cell = $('<td></td>').append(idField).append(moreFields);
var row = $('<tr></tr>').append(cell);
$(sendingInputField).parents("tr").after(row);
SetFocusEventForInputs(className);
}
</script>
<table>
<tr>
<td>
<input name="RowItems[0].Id" type="text" class="unSelected0" />
<input name="RowItems[0].MoreFields" type="text" class="unSelected0" />
</td>
</tr>
</table>
The default model binder in MVC should resolve it just fine when it gets posted
[HttpPost]
public ActionResult YourPostActionHere(PageModel model)
{
var count = model.RowItems.Count();
etc...
}
You can do it the same way, because in the code example above, you are using jQuery which is also supported (of course) with ASP.NET MVC.
Perhaps I don't understand you, but I don't see any PHP code in the code example above.
what you want to do is a client side script that is not depend on PHP or Asp.Net so it does not matter what your code is written by. this should work in Asp.Net mvc too.
if you want to collect the new control data to use it in server side you can collect it by JavaScript and assign it in a hidden field that can be accessed in server side. you can use one hidden field by save the values in one string and separated by any delimiter.
Are you possibly just missing the script tags? Like the others said, javascript is platform independent.
<tr class="unSelected">
<input name="id[]">
<input name="blabla[]">
</tr>
<script src="/Scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function () {
$('.unSelected').focusin(function () {
if ($(this).hasClass('unSelected')) {
var row = $(this).clone(true);
$(this).after(row);
$(this).removeClass('unSelected');
}
});
});
</script>
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>