I am creating a asp.net web application and I want to know how to call, code behind method in javascript. Following Java script shows that getting the values of multiple textboxes with same name in to array.
using code behind method, I try to pass the values of an array ,but it didn't works. when I am using alert box, it display the textbox values .
function JavaScriptFunction() {
var arr = $("input[name='multiple[]']");
$.each(arr, function (i, item) {
alert($(item).val());
});
}
When I am call code behind method before alert box method, then it won't display any message box. (Testing code behind method)
function JavaScriptFunction() {
var arr = $("input[name='multiple[]']");
$.each(arr, function (i, item) {
PageMethods.setemail("Paul Hayman");
alert($(item).val());
});
}
This is my testing code behind method. TextBox1 I used just for testing.
[WebMethod]
public void setemail(string p)
{
TextBox1.Text = p;
}
Then finally I import webService reference.
using System.Web.Services;
This is I used webforms for button
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="JavaScriptFunction()" OnClick="Button1_Click" />
WebMethod can't interact directly with the DOM. WebMethods are outside the scope of the normal page model.
In fact, WebMethod is no longer supported by MS and you shouldn't use it. Instead, if you're on .NET 4.5 you can create a Web API and call into it with AJAX (jQuery has great helper functions for this, I see you tagged it). The Web API will return the string, and then you can use JavaScript to set the text of the textbox.
Web API
public class TestController : ApiController
{
public string GetHello(string name)
{
return String.Format("Hello, {0}!", name);
}
}
Then the jQuery AJAX code:
$.ajax({
url: '/api/test/GetHello?name=Nade',
type: 'GET'
})
.success(function(output){
$('#TextBox1').val(output);
});
If you're not on .NET 4.5, upgrade! If upgrading isn't possible, then you could just set up a generic handler (.ashx) and write to the response.
Related
I am calling an static web method, the method is written in an aspx.cs file having two public classes:
public class Employee
{
public string EmployeeNumber;
public string FullName;
public string LoginName;
public string EmailID;
public string Phone;
}
public partial class CustomWebMethods : LayoutsPageBase
{
[WebMethod]
public static List<Employee> GetEmployeeDetails(string employeeLoginName)
{
List<Employee> lstEmployeeDetail = new List<Employee>();
//do something
return lstEmployeeDetail;
}
}
If I keep the public class employee in the same page then ajax call is working fine.
But if I move the employee to another class library project and add reference of that project, ajax call is not working. Why?
Javascript method not able to call the web method at all.
This is because of WebMethod attribute internal works. When you mark some method with this attribute, it will be available through PageName.aspx/MethodName url.
Then, after moving this method to outer library, you moving it from the page methods too, and after that it's not available.
So, if you want to refactor your code, you have to add the WebService to your project, from that class you can call methods from other library.
You can also create a javascript proxy on your client like this:
<asp:ServiceReference InlineScript="true" Path="~/CustomersService.asmx"/>
Or use the ScriptManager for it, like this:
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
After that you can use this proxy instead of ajax call.
<script type="text/javascript">
function Add()
{
var x = $get("txtX").value;
var y = $get("txtY").value;
PageMethods.Add(x, y, OnWSAdd);
}
function OnWSAdd(result)
{
$get("spanAddResult").innerHTML += result;
}
</script>
Old, but great article about Understanding ASP.NET AJAX Web Services.
I am developing a WinRT application and was wondering if i could link a Hyperlink tag to a JavaScript function or be able to call the view page with NavigateUri? Or if it is possible to use interaction triggers that call the JS by a command.
==Update==
I have been testing different xaml tags from hyperlink to hyperlinkbutton. HyperlinkButton seems to appear and is clickable. it is just the on click function that doesn't seem to get called...
<HyperlinkButton Grid.Row="1" Click="__Title__.OnBuildingClick" Content="Buildingoo"/>
<HyperlinkButton Grid.Row="1" Click="__Title__.OnBuildingClick" Content="Buildingoo" ?
<i:EventTrigger EventName="ClickHyperlink">
<behaviors:EventToScriptBehavior Command="__Title__.OnBuildingClick" />
</i:EventTrigger>
</i:Interaction.Triggers>
</HyperlinkButton>
these are the 2 approaches i have taken. The functino onBuildingClick is only an alert msg but it doesnt get called..
Assuming the webView has a predefined name "currentWebView":
<WebView x:Name="currentWebView" ... />
You can access the control from the codebehind using its name, and then tell the web view to search the DOM for a javascript function by name, and invoke it if the function exists.
To invoke a method by name you will use the C# Method "InvokeScript" and pass 2 parameters:
Param 1: Name of Javascript function
Param 2: Comma Separated List of Arguments in order of Javascript Signature
currentWebView.InvokeScript("nameOfFunction", "myFirstparam, secondParam, thridParam");
Additionally, in order to allow the XAML UI to respond to the Javascript event your Javascript code must call
nameOfFunction(param1, param2, param3){
window.external.notify("This content will be accessible in the next steps NotifyEventArgs e.Value property.")
};
and in the last piece of wiring up the ability to respond to Javascript from C#, you must apply an event handler in the C# codebehind to allow the XAML to be notified what is going on inside the WebControl
// In the Constructor / OnLoaded/ OnNaviagtedTo Event of the code behind
currentWebView.ScriptNotify += new NotifyEventHandler(currentWebView_ScriptNotify);
... then later in the class
private void currentWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
//can access the value included in the notification
var notification = e.Value;
someTextblock.Text = notification;
}
Putting It Together:
<HyperlinkButton x:Name="btnExecuteJavaScript" Grid.Row="1" Click="btnExecuteJavaScript_Click" Content="Buildingoo"/>
public void btnExecuteJavaScript_Click(object sender, RoutedEventArgs e)
{
currentWebView.InvokeScript("OnBuildingClick", "arbitraryParameter, mayNotBeNeeded");
}
I am trying to figure out the correct javascript syntax for a DevExpress datagrid callback to pass data back to the client.
In the .aspx I installed an onclick event in the DataGrid row with a CustomCallback event using the js call: dg.PerformCallback(key); and in the aspx.cs file this function is correctly reached, however I cannot pass data back to the client:
protected void dg_CustomCallback(
object sender,
DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
{
string key = e.Parameters; // works
e.Results = "something"; // .Results does not exist
return;
}
Then I switched from a CustomCallback to a DataCallback because the DevExpress.Web.ASPxGridView.ASPxGridViewCustomDataCallbackEventArgs does have a .Results property. However, I cannot figure out the corresponding javascript call. I tried in vain: dg.PerformCallback(key); , dg.PerformDataCallback(key); and dg.SendCallback(key);
Also I am wondering, when the above problem is fixed, which js function I need to program to receive the return data from the server after the callback.
What you are trying to achieve can be done using the JSProperties on callback and the OnEndCallback client side event of the ASPxGridview. This aspx tag can be placed exactly after the </Columns> closing tag of the ASPxGridview.
<ClientSideEvents EndCallback="function(s,e)
{
var errText = s.cpError;
if (errText != "")
{
alert(errText);
}
}" />
On the server side you set the JSProperties like this
gridOfApp.JSProperties["cpError"] = "The error was major!";
Important. Bear in mind that your JSProperties MUST ALWAYS start with the cp prefix.
I am doing amendments in my MVC application in order to disallow users to open more than one tab/ window within a single session.
I am taking reference of this article (click here) in order to do that.
This article is written for asp.net whereas I need to implement this feature for ASP.NET MVC.
I think all this should be possible in MVC, however, I am not sure what should I do to re-write this
if(window.name != "<%=GetWindowName()%>")
GetWindowName() is a function I have created in my Controller, and it returns a value of "WindowName" key from Session object. How can I read its value in above javascript?
You can write a controller method for that:
public ActionResult GetWindowName()
{
Session["WindowName"] =
Guid.NewGuid().ToString().Replace("-", "");
return Json(Session["WindowName"].ToString());
}
Then call it through ajax:
$.get('#Url.Action("GetWindowName")', function(data){
if(window.name != data) {
// do what you need to do here
}
})
You can use ajax for that (jQuery):
$.get('#Url.Action("GetWindowName")', function(result){
if(window.name != result)
//...
});
This is razor syntax...
I am trying to call a function from a Silverlight application. It should be a very simple task to do but so far I am not getting the result that I am looking for.
This is my Silverlight code:
private void button2_Click(object sender, RoutedEventArgs e)
{
HtmlPage.Window.Invoke("SayHello", new string[] { "Salut!" });
}
And this is the JavaScript code :
function SayHello(theid) {
alert(eval(theid));
var divStatusDiv = document.getElementById("divStatus");
divStatusDiv.style.backgroundColor = "Red";
}
The alert message always show "undefined" but when I press "OK" the colour of that DIV gets changed to Red as it should be.
Why am I getting "Undefined" all the time ?
You need to create the json that can be passed properly instead of just passing along an array like that. You can simply return "Salut!" instead of new string[] { "Salut!" } or you can create the json array for the string array you have.
I'm not familiar with Silverlight, but if theid has value "Salut!" inside of SayHello, then you cannot eval it, since it is a string of text, not code. You should change the line alert(eval(theid)); to just alert(theid);.
Use
alert(eval(theid.value));