I want to run function inside web service (.asmx file)
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Admin/WebSrvcs/Management.asmx/f_SearchLabel',
data: "{_sQuery:'" + obj.value + "'}",
dataType: "json",
But I don't know where will be my root url(http://localhost:4399/VirDir or something else it may be) address inside js file. And i need to reach root folder of application to find asmx file.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'http://localhost:4399/virDir/Admin/WebSrvcs/Management.asmx/f_SearchLabel',
data: "{_sQuery:'" + obj.value + "'}",
dataType: "json",
I am working on Visual Studio 2008 and building web site with C#.
any help would be greatly appreciated
If you're using Master Pages then this becomes handy:
In the HEAD of Master Page:
<script type="text/javascript">
var baseUrl = '<%# ResolveUrl("~/") %>';
function ResolveUrl(url) {
if (url.indexOf("~/") == 0) {
url = baseUrl + url.substring(2);
}
return url;
}
</script>
In the Master Page .cs page:
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}
Then in your javascript:
ResolveUrl("~/Admin/WebSrvcs/Management.asmx/f_SearchLabel")
Maybe Im missing something, but if the javascript and the page are on the same server you can just use js to do something like this:
<script>
var pd = parent.document;
var location = pd.location.protocol + "//" + pd.location.host;
alert(location);
</script>
Also, you could write an HTTP handler for your javascript, and when the request comes in, you could fill in a variable by getting the full url of the request.
internal static string GetFullPath(HttpRequest request)
{
Uri uri = request.Url;
string fullUrl = String.Format("{0}{1}{2}{3}", (request.IsSecureConnection) ? "https://" : "http://",
uri.Host, (uri.IsDefaultPort) ? "" : String.Format(":{0}", uri.Port), uri.AbsolutePath);
Int32 index = fullUrl.LastIndexOf("/");
fullUrl = fullUrl.Remove(index + 1, (fullUrl.Length - 1) - index);
return fullUrl;
}
There are some ways you could do this.
One would be to iterate over the <script> elements on the page and check if the src attribute contains the desired script name (e.g. <script src="my/js/dir/myScript.js"></script>) and then extract the path you want.
Although this could be an easy way to port things across other servers, you could have the problem that "myScript.js" could be included more than once in different locations, so it wouldn't be that much reliable.
Another way to do this would be to include some sort of configuration file where you could set up your application settings, using something like this:
File: app-config.js
var AppConfig = {
"someImportantPath" : "some/important/path",
"anotherPath" : "another/path"
}
And the you would use this global variable across your application.
Related
I am sending a complex string (which is a combination of the style attribute, ID and label text) from the script using $.ajax() . I went through a couple of questions on similar problems. But maybe I am not able to understand where am I getting it wrong.
This is the script I am using :
$(".btnSaveStyle").click(function (e) {
var comp1Style = "";
var comp2Style = "";
$(".box").children(".comp1").each(function () {
var style = $(this).attr('style');
var title = $(this).text();
var componentClass = $(this).attr('class');
comp1Style = comp1Style + style + "#" + componentClass + "#" + title + "$";
});
alert(comp1Style); //I get the style here
$.ajax({
type: "POST",
async: true,
url: 'AjaxRecieveStyle.aspx/GetStyle',
data: comp1Style
});
And in the C# I am accessing it in the following way :
[WebMethod]
protected void GetStyle(string style)
{
var recievedStyle = style;
Customer customer = (Customer)Session["existing_user"];
if (customer != null)
{
EventComponent eventComponent = new EventComponent();
string txtComp1 = recievedStyle;
string[] separateComponents = txtComp1.Split('$');
string[] individualComponent = new string[5];
foreach (string position in separateComponents)
{
individualComponent = position.Split('#');
if (individualComponent[0].Equals(""))
{
//do nothing
}
else
{
eventComponent.EventID = 1;
eventComponent.Image = "";
eventComponent.Style = individualComponent[0].ToString();
eventComponent.ComponentType = individualComponent[1].ToString();
eventComponent.Title = individualComponent[2].ToString();
int id = new EventComponentLogic().Insert(eventComponent);
}
}
}
}
Now :
1) : Should I use a JSON object to pass the data ?
OR
2) : Please show me what am i doing wrong in here ?
1) Yes it's better to send data using JSON - I mean, it'd be much easier to understand what's happening when anyone will look at that code in a year from now. And it's also much easier to extend the protocol based on JSON.
2) I suggest you to add logging at the very beginning of the GetStyle(string style) method. Then please try to get to it by explicitly typing the URL in your browser (or better using PostMan - see below for a link, PostMan will help you with testing POST requests as I see you have a POST request there) and ensure that the web-server code works.
And only if it works then please try your front-end AJAX request.
I suppose that you don't handle POST request correctly in your WebAPI. It will only handle GET requests. Please look at this SO question for details: Simple post to Web Api
3) Link to PostMan: https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
Did some digging and came up with this link: http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
The source code from the website shows that you may be missing some key features in your ajax call:
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
While this is (obviously) intended for their example you see that they set the following attributes that you do not
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
While the success and failure attributes are definitely optional I believe that setting your content type and datatype would really help you out here.
I changed my script to the following :
$.ajax({
type: "POST",
async: true,
url: 'AjaxRecieveStyle.aspx',
data: { style: comp1Style } //as I want to pass the parameter 'style' which is internally a JSON array.
});
I fetched the variable style in my C# in the following way (without using [WebServices]) :
I wrote a method GetStyle(string style) to get the data being sent from the ajax call.
Note: I did not call AjaxRecieveStyle/GetStyle from my script as the method is not accessible in my C# method . The data is actually received from the Page_Load method.
I access the variable sent from the script using Request.Params["style"].
My C# method is :
protected void Page_Load(object sender, EventArgs e)
{
GetStyle(Request.Params["style"]);
}
protected void GetStyle(string style)
{
var recievedStyle = style;
//do something on the recieved data!
}
This wil be an alternative to anyone who don't want to send JSON data actually !But sending data using JSON format will increase the readability of the code..
Here's my ajax call:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());
console.log($(this).prop("name") + "=" + $(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default",
type: "POST",
dataType: "json",
data: { filterValues: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
And my server side code:
public partial class tools_oppy_Default : System.Web.UI.Page
{
...
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
string checkedBoxes = Request["filterValues"];
testLabel.Text = checkedBoxes;
}
I'm just trying to obtain the post URL with the appropriate checked values so I can parse it on the server. However, I'm having trouble obtaining the URL. The string checkedBoxes is supposed to hold a query string like name=value&name=value&name.... but when I test it, the testLabel doesn't show anything. I'm using web forms app, not MVC. Also, I'm new to ajax and their behavior. Thanks.
First, I assume that the url in you JQuery call is valid as there is not aspx extension their.
Second, It looks like what you need to do is create a web method and call it from JQuery for example the following is a web method that accept string
[WebMethod]
public static string GetData(String input)
{
return DateTime.Now.ToString();
}
and you can call it using the same way with your current code just update the url parameter to include the method name
url: "PageName.aspx/MethodName",
for more details about web methods and their union with JQuery please check this article
Edited The following is complete sample
The web method should look like the following one
[WebMethod]
public static string GetData(string filterValues)
{
return filterValues; //This should be updated to return whatever value you need
}
The client side part of calling the web method should look like the following
$.ajax({
url: "/Default/GetData",
type: "POST",
contentType: "application/json; charset=utf-8", //I have added this as "contentType" parameter represents the type of data inside the request meanwhile the "data" parameter describes the data inside the response
data: "{ filterValues:\"" + filterCheckboxes + "\"}", //Note that I have updated the string here also set the name of the parameter similar to the input of the webmethod
dataType: "json",
success: function (result) {
alert(result.d);//You should access the data using the ".d"
}
});
One last thing, If you are using asp.net permanent routing the above code will not work and you should disable it by updating the file "App_Code/RouteConfig.cs" From
settings.AutoRedirectMode = RedirectMode.Permanent;
To
settings.AutoRedirectMode = RedirectMode.Off;
And remember to clear browser cache after the above update
I have FriendlyUrls nuget package added to WebForm application.
In RegisterRoutes I have:
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Off;
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
I created 2 pages WebForm1.aspx and WebForm2.aspx
On WebForm1.aspx I referenced jQuery v1.9.1 in the head simply added the following inside the default div tag in the body:
<div id="dvResult"></div>
<script type="text/javascript">
$(function() {
$.fpm("GetCategories", '', function (res) {
$("div#dvResult").html(res.d);
}, function (xhr, ajaxOptions, thrownError) {
$("div#dvResult").html("<b>" + thrownError + "</b><br/>Status: " + xhr.status + "<br/>" + xhr.responseText);
});
});
$.fpm = function fpm(methodName, arguments, onSuccess, onError) {
var proto = (("https:" == document.location.protocol) ? "https://" : "http://");
var hostname = window.location.hostname;
if (window.location.port != 80)
hostname = window.location.hostname + ":" + window.location.port;
var loc = proto + "" + hostname + "/WebForm2.aspx";
$.ajax({
type: "POST",
url: loc + "/" + methodName,
data: "{" + arguments + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
error: onError
});
};
</script>
WebForm2.aspx is kept stock standard after adding the file to the project, except for 1 method added to the code behind:
[System.Web.Services.WebMethod(EnableSession = false)]
public static string GetCategories()
{
return "hi";
}
When I run the page WebForm1.aspx I get the following result:
{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
When view the request in fiddler I can see the friendly url did not strip the .aspx extension (which is a good thing):
http://localhost:14918/WebForm2.aspx/GetCategories
However as shown above, the FriendlyUrlSettings has the AutoRedirectMode set to RedirectMode.Permanent and when you uncomment the line for RedirectMode.Off and comment the Permanent out, then you actually get the result "Hi" printed on the screen.
Anyone has any ideas what the cause could be or how to add an exclusion to the routes?
I have tried to following but it does not seem to affect in any way the 401 result I keep getting:
//routes.Add(new Route("*Remote.aspx*", new StopRoutingHandler()));
//routes.Ignore("{remote}", new { remote = #".*\Remote.aspx(/.)?" });
You just saved my day.Below is the c# version of the code.In case of the master pages just paste PageMethods.set_path("default.aspx") before closing Content tag
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings, new CustomFriendlyUrlResolver());
}
public class CustomFriendlyUrlResolver : WebFormsFriendlyUrlResolver
{
public override string ConvertToFriendlyUrl(string path)
{
if (HttpContext.Current.Request.PathInfo != "")
{
return path;
}
else
{
return base.ConvertToFriendlyUrl(path);
}
}
}
This is late but in case someone has same issue. Simple fix, set RedirectMode.Off instead of RedirectMode.Permanent. For the Ajax part do the following for the url key:
$.ajax({
type: "POST",
url:'<%=ResolveUrl("sample.aspx/methodname")%>'
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Worked");
},
failure: function (msg) {
alert("Failed");
}
});
I had similar issue, the above solution worked for me. This is a quick fix but I wouldn't recommend it for production. This error occurs partly because of the FriendlyUrl vs non FriendlyUrl redirect method settings hence the server is receiving requests from an unauthenticated user. For production, make sure to put in place necessary security details and accept request from authenticated users otherwise the exposed methods from code behind can cause a huge security risk.
Faced with stripping vast amounts of PageMethods from a large established application, I found the following alternative solution to switching over to WebApi (turning AutoRedirectMode off still allows my file extensions to be displayed when requested directly and I really don't want that).
Instead use a custom FriendlyUrls.Resolver in your App_Start/RouteConfig file. The only change to existing pages was to add the following markup to each page using PageMethods:
<script>PageMethods.set_path("/Pages/Subjects.aspx")</script>
Here is the sample code in VB:
Imports Microsoft.AspNet.FriendlyUrls
Imports Microsoft.AspNet.FriendlyUrls.Resolvers
Public Module RouteConfig
Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.EnableFriendlyUrls(New FriendlyUrlSettings() With {.AutoRedirectMode = RedirectMode.Permanent}, New IFriendlyUrlResolver() {New CustomFriendlyUrlResolver()})
End Sub
End Module
Public Class CustomFriendlyUrlResolver
Inherits WebFormsFriendlyUrlResolver
Public Overrides Function ConvertToFriendlyUrl(path As String) As String
If HttpContext.Current.Request.PathInfo <> "" Then Return path Else Return MyBase.ConvertToFriendlyUrl(path)
End Function
End Class
Hope that helps someone!
Ended up creating WebApi project and after a few new problems arriving (CORS related), got it working and actually feel that it's probably a better solution than pagemethods.
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.
Hi
I used jquery in my application and I have a problem but I think it is necessarly to look at this code :
$("#btnAddToBasket").click(function () {
var id = $("#ProductIDAtBasket").text();
var count = $("#BasketAddedValueText").val();
//ajax request
$.ajax({ type: "Post",
url: "Services/NewE_ShopServices.asmx" + "/" + "GetPrice",
data: "{" + "count" + ":" + count + ", goodcode : " + id + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
async: true,
cache: false,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
var res = result.d;
res = res.split(';');
$("#spanFinalPrice").text(res[2]);
$("#spanAbsolutePrice").text(res[3]);
$("#spanDiscount").text(res[4]);
$("#spanCount").text(res[1]);
$("#AddBasketDiv").hide("slow");
}
function AjaxFailed(result) {
alert(result.responseText);
}
As you can see at the following there is ajax send method to web service I get the values and put results using ajaxsucceeded method into the page it works fine and suitable but my problem is that it is basket viewer and I want to be more permanent for example in this page when you go to other page and back to it the contains will be omitted I can use session and cookies in the webservice class but how I can read from jQuery code? what is solution is there any other solution ?
If I am understanding it correctly, you are adding things to a basket, but they are not persisting on other pages? I.E, you add a product to your basket, and then move to another page and the item is not in the basket?
If so you need to check a couple of things:
How are you storing the basket on the server side. Do you put the items in Session?
Are you reading from that basket to pre-populate the basket in a state before you add items in?
I just add another ajax method to my jquery script and put some sever side property and set them by ajax method that was easiest.