I am using Asp.net/C# in my project , i have a requirement where in the user enters a name and the details of that person is displayed asp.net gridview ,,,, i am planning to use html button instead of asp.net button because the results displayed will be in tab...However the function which will populate the gridview is in code behind ,, so my question is how will i call that method from jquery,,, is that possible.Or is there any better way of doing this......
Thanks in advance
Have look to this post which describe you how to call function of code behind : Calling Server Side function from Client Side Script
Cs File (codebehind)
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
Javascript/jQuery
function IsExists(pagePath, dataString)
{
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
},
success:
function(result) {
alert( result.d);
}
}
});}
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'ab" }";
IsExists(pagePath, dataString);
Related
I'm using $.ajax({...}); to send some data to my server (the aspx's CodeBehind file in c#). In order to receive this data to work with in the CodeBehind file, I have to use a static WebMethod ([System.Web.Services.WebMethod]). Once I work with this data, I want to either redirect them to a new page if there was a success (In my case, a successful credit card charge), otherwise, send an alert to the user that something went wrong (i.e., credit card charge randomly didn't work).
Is there a way to access/alter the current page's markup via this static WebMethod (e.g., add <script>alert("Something went wrong")</script>), without the ability to use asp page controls? (i.e., this which is the page in non-static methods in CodeBehind files)
You may need to use Success and Failure section of $.ajax syntax. Please refer an example below. I hope your web method returns string to make this work.
Sample WebMeethod
[ScriptMethod()]
[WebMethod]
public static string YourWebMethod()
{
String yourMessageString = String.Empty;
//process as per your logic
yourMessageString = "Some Message";
return yourMessageString;
}
$.ajax({
type: "POST",
url: "/yourpage.aspx/yourwebmethod",
async: false,
contentType: "application/json; charset=utf-8",
data: "your data",
dataType: "json",
success: function (message) {
alert(message);
},
error: function () {
alert("error");
},
failure: function () {
alert('failure');
}
});
I am trying to call the following webmethod found in one of my aspx page files:
[WebMethod]
public static string GetReportDetails()
{
var reportDetails = DataAccess.Database().GetBusinessInterestReportDetails(HttpContext.Current.User.Identity.Name);
var json = BusinessInterestReport.GetJson(reportDetails);
return json;
}
And this is the javascript that i'm using to call the webmethod:
$.ajax({
type: 'POST',
url: 'SummaryReport.aspx/GetReportDetails',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error has occured: ' + errorThrown);
}
});
The javascript that makes this ajax call:
$('.reportOption').click(function (e) {
$.ajax({
type: 'POST',
url: 'SummaryReport.aspx/GetReportDetails',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error has occured: ' + errorThrown);
}
});
})
The ScriptModule config is already in the web.config. The break point is not even getting hit on the webmethod and the entire page's content is returned. Any idea what's causing this?
EDIT:
Using Chrome's debug console I found this error:
[ArgumentException: Unknown web method GetReportDetails.
Parameter name: methodName]
System.Web.Script.Services.WebServiceData.GetMethodData(String methodName) +516665
System.Web.Handlers.ScriptModule.OnPostAcquireRequestState(Object sender, EventArgs eventArgs) +168
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Why would it not pick up the method name? I've also enabled PageMethods using <asp:ScriptManager ID="smMain" runat="server" EnablePageMethods="true" />
P.S. Just realized that i'm calling it from within an iFrame. Could this have anything to do with the issue?
I think you need to explicitly add contentType, as its default value is application/x-www-form-urlencoded; charset=UTF-8, which is not you are after.
So you might want to revise your jQuery code a bit.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SummaryReport.aspx/GetReportDetails",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error has occured: ' + errorThrown);
}
});
Remove the static keyword from your GetReportDetails method.
Don't write plumbing code (JSON serialization/deserialization) in your web method. Simply take/return models (.NET POCO objects):
[WebMethod]
public static string GetReportDetails()
{
var reportDetails = DataAccess.Database().GetBusinessInterestReportDetails(HttpContext.Current.User.Identity.Name);
return reportDetails;
}
and then consume:
$.ajax({
type: 'POST',
url: 'SummaryReport.aspx/GetReportDetails',
contentType: 'application/json',
success: function (data) {
// the actual object will be inside data.d
var reportDetails = data.d;
// Now you could directly use the properties of your model
// For example if your ReportDetails .NET type had a string property
// called FooBar you could directly alert(reportDetails.FooBar);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error has occured: ' + errorThrown);
}
});
Things to notice:
We have explicitly specified the contentType: 'application/json' to indicate to the web method that we want to use JSON as transport mechanism
We have gotten rid of the dataType: 'json' property because jQuery is intelligent enough to use the Content-Type response header and automatically parse the data parameter that is passed to your success callback.
I would also recommend you reading this article about consuming ASP.NET PageMethods directly from jQuery.
Fixed it. It turns out that the inherits attribute was missing at the top of the aspx file.
So now I have:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SummaryReport.aspx.cs" MasterPageFile="~/MasterPages/SummaryReports.Master"
Inherits="Web.SummaryReport"
%>
An addition I would like to contribute here from my experience in this problem.
if you are using a content page or master page, you can't call the WebMethod by accessing the page ,instead add a webserivce page and use it, please refer to this link it worked with me.
http://forums.asp.net/post/5822511.aspx
I copied it here
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function MyFunction() As String
Return "Hello World"
End Function
Then you can call the webmethod from master page or content page like following:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function MyFunction() {
var request = $.ajax({
type: 'POST',
url: 'HelloWord.asmx/MyFunction',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (serverdata) {
alert("Done " + serverdata);
},
error: function (error) {
alert("error ");
}
});
return false;
}
</script>
please be sure to uncomment the line :
System.Web.Script.Services.ScriptService
in the webservice page since when creating the page it will be commented
I have the follow line in my Javascript code
credenciadausuario = '<%= getCredenciada() %>';
In my code-behind I have this method
public string getCredenciada()
{
Utilidade.QuebraToken tk = new Utilidade.QuebraToken();
string credenciada = tk.CarregaToken(1, Request.Cookies["token"].Value);
return credenciada;
}
but when I put the debugger in my javascript code, the credenciadausuario variable, receives the string "<%= getCredenciada() %>" and not the return of my method. How can I call my method that are in my code-behind via javascript or jquery ?
It seems all you want to do in your code is get the value of a cookie. Why not do that in JavaScript on the client?
IF possible make use of ajax and do call the method, that will do you task.
check this post : http://pranayamr.blogspot.com/2012/01/calling-server-side-function-from.html
Cs File (codebehind)
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
Javascript
function IsExists(pagePath, dataString)
{
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
},
success:
function(result) {
alert( result.d);
}
}
});}
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'ab" }";
IsExists(pagePath, dataString);
This article from Encosia is excellent. It shows how to call a method in your code behind using jQuery ajax.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
In your code behind you have to give the method the [WebMethod] attribute:
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
To call that method using jQuery you would use the following:
$.ajax({
type: "POST",
url: "PageName.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Well, to actually CALL your code-behind methods from Javascript, you would have to use ajax. JQuery has a nice $.ajax wrapper for that.
But I think you just want to include some value into the js code once, while it's being generated and sent to the browser. In that case, you need to use a file type which ASP.NET recognizes as a dynamic file.
The easiest would be to put JS code (in a <script> tag) into .ascx files. Then <%= getCredenciada() %> will be executed and will return an actual string which will be rendered into javascript code.
Then, of course, you should include such a control to the page as a regular ASP.NET control.
And I am not saying this is the best way to achieve what you want. Sometimes it's just the fastest.
I want to call a C# function in my aspx.cs file with jQuery. The function looks like:
protected void Fill(object sender, EventArgs e) { ...do s.th. with sender... }
in the function im getting my control I want to work with by doing a cast on the sender. How to pass the sender to server with jquery?
Check this : Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages
OR
Hi you can check this article : http://pranayamr.blogspot.com/2012/01/calling-server-side-function-from.html which dicuss about calling server method with the jQuery function.
cs file i.e serverside code
[WebMethod]
public static string IsExists(string value)
{ return "True"; }
Client script
function IsExists(pagePath, dataString, textboxid, errorlableid) {
//alert(pagePath);
$.ajax({
type: "POST",
url: pagePath,
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown) {
$(errorlableid).show();
$(errorlableid).html("Error");
},
success:
function(result) {
var flg = true;
if (result != null) {
debugger;
flg = result.d;
if (flg == "True") {
$(errorlableid).show();
}
else {
$(errorlableid).hide();
}
}
}
});
}
function focuslost() {
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'" + $("#<%= txtData.ClientID%>").val() + "' }";
var textboxid = "#<%= txtData.ClientID%>";
var errorlableid = "#<%= lblError.ClientID%>";
IsExists(pagePath, dataString, textboxid, errorlableid);
}
You can't call functions just like that with jQuery. jQuery is a client scripting technology based on javascript that runs on the client browser. It doesn't know what ASP.NET is. It even less knows what a server side, ASP.NET code behind method is.
This being said, you could send an AJAX request to a server side script which in your case could be either a generic handler (.ASHX) or an .ASPX page. In this second case you could use Page Methods.
I have a problem with a master page containing a asp:textbox that I'm trying to access using jQuery. I have read lot sof thread regarding this and tried all the different approaches I have seen, but regardless, the end result end up as Undefined.
This is the relevant part of the MasterPage code:
<p><asp:Label ID="Label1" AssociatedControlID="osxinputfrom" runat="server">Navn</asp:Label><asp:TextBox CssClass="osxinputform" ID="osxinputfrom" runat="server"></asp:TextBox></p>
When I click the button, the following code from a jQuery .js file is run:
show: function(d) {
$('#osx-modal-content .osxsubmitbutton').click(function (e) {
e.preventDefault();
if (OSX.validate()){
$('#osx-modal-data').fadeOut(200);
d.container.animate(
{height:80},
500,
function () {
$('#osx-modal-data').html("<h2>Sender...</h2>").fadeIn(250, function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{'from':'" + $("#osxinputfrom").val() + "','mailaddress':'" + $("#osxinputmail").val() + "','header':'Test3','message':'Test4'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Meldingen er sendt!</h2>');
$('#osx-modal-data').fadeIn(200);
});
},
error: function(msg){
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Feil oppstod ved sending av melding!</h2>');
$('#osx-modal-data').fadeIn(200);
});
}
});
});
}
);
}
else{
$('#osxinputstatus').fadeOut(250, function () {
$('#osxinputstatus').html('<p id="osxinputstatus">' + OSX.message + '</a>');
$('#osxinputstatus').fadeIn(250);
});
}
});
},
So the problem here is that $("#osxinputfrom").val() evaluated to Undefined. I understand that the masterpage will add some prefix to the ID, so I tried using the ID from the page when it's run that ends up as ct100_osxinputfrom, and I also tried some other hinds that I found while searching like $("#<%=osxinputfrom.ClientID%>"), but it ends up as Undefined in the method that is called from the jQuery ajax method anyway. The third and fourth parameters to the ajay function that is hardcoded as Test3 and Test4 comes fine in the C# backend method.
So my question is simply: How can I rewrite the jQuery selector to fetch the correct value from the textbox? (before I used master pages it worked fine by the way)
Best regards
Daemon
It will be abit slower but why dont you try adding cssclass="bla" to your label and then get it with $('.bla').val(); ?
You should use the attribute ends with selector
Link
it would be $("id$='osxinputfrom'")