Call method in code-behind (secure page) from client (JavaScript) - c#

Let me start of by saying I am very new to ASP.NET and C#.
I have a simple web form containing data which I want to send to a code-behind page.
The idea is to capture the data and send it as a JSON object to a code-behind method.
Note that this is done via JavaScript/AJAX (see code below).
The code-behind method will then do a trivial HTTP "PUT" request to update the data.
The .apsx page is located in the Secure folder (uses a Secure Master).
Don't know if that will affect the method calling?
Following is the code I have thus far.
JavaScript/AJAX:
var saveOptions =
{
url: "Profile.aspx/UpdateVendor",
type: "PUT",
dataType: 'json',
data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
contentType: "application/json",
success: function (response)
{
}
}
Code-behind:
namespace PartyAtVendors.Secure
{
[WebService]
public partial class Profile : System.Web.UI.Page
{
[WebMethod]
public static bool UpdateVendor(PartyAtApi.Models.Vendors vendor)
{
return true;
}
}
}
Update:
Problem is as follows. The codebehind method isn't called. When I run and test the code and use Chrome's "inspect element" I receive the error:
PUT http://localhost:50671/Secure/Profile.aspx/UpdateVendor 404 (Not Found)

Such static methods are called Page Methods in asp.net.
You call them form javascript like this on the same page as follows:
string data = "{mydata:myvalue}";
PageMethods.UpdateVendor(data);
You need to have a ScriptManager on the page and it should have PageMethods enabled
<asp:ScriptManager runat="server" EnablePageMethods="true">
</asp:ScriptManager>
The page method must be defined on the page. It cannot be defined in a control, master page, or base page.
PageMethods only support HTTP POST(Even when you call them without the javascript proxy of PageMethods). You can read the details of this security limitation in this blog post by Scott Guthrie. Using the PUT verb is causing the 404 error.
ASP.NET AJAX 1.0 by default only allows the HTTP POST verb to be used
when invoking web methods using JSON

Your webmethod & javascript method should be on same page.

Hi managed to sort out what was wrong.
I simply changed the HTTP method to "POST" as follows:
var saveOptions =
{
url: "Profile.aspx/UpdateVendor",
type: "POST",
dataType: 'json',
data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
contentType: "application/json",
success: function (response)
{
}
}
$.ajax(saveOptions);
This seemed to fix the problem and now I am able to send the JSON data to the codebehind method using AJAX.

Related

In ASP.NET Web Forms, how to call a page method using "get" request

In ASP.NET Web Forms, i am able to call page method using Ajax "post" request. But i am not able to call the page method using "get request".
In this case, is it possible to call page methods using "Get" request.?Could you please provide any suggestion for this?
Example Code for Page method:
[WebMethod]
public static string GetData()
{
return "test";
}
As #vc mentioned in the comments you'll need to make use of the ScriptMethodAttribute as well as WebMethod because you want your request to be GET and not POST so change your code as follows:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetData()
{
return "test";
}
And in the markup you can do
function ShowTestMessage() {
$.ajax({
type: "GET",
url: "YourPage.aspx/GetData",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
<input id="ButtonId" type="button" value="Show Message"
onclick = "ShowTestMessage()" />
Don't forget to add the following reference
using System.Web.Script.Services;
using System.Web.Services;
Ajax GET requests to an ASP.NET Page Method?
I guess the link would be useful. It says For security reasons, ASP.Net AJAX page methods only support POST requests.
Tried decorating the method with [ScriptMethod(UseHttpGet = true)]
but still the get request is not hit.
Also the msdn doc for [ScriptMethod(UseHttpGet = true)]
quotes When this property is set to true, the client proxy code uses HTTP GET to call the Web service. Not sure if it works for a webmethod in web forms.
P.S : Well seems to work with the newer versions of Jquery 2.2.2. Also please be sure that you send data through query strings not using request body as in POST method.

Update the Page without refresh it

Goal:
When you click on the row (1), new data shall display (3.) without the whole webpage will be updated/refreshed.
Problem:
1.
I need advice and I don't know where to find the funciton to display the picture number 2 and how to display the data and new object (3.) without update/refresh the whole webpage?
And
2
How do you create an icon to display loading picture?
Information:
- The page is based on ASP.mvc with C#
Use ajax functionality of either jquery or MVC ajax helpers.
You can find jquery ajax here.
and MVC ajax helper lib here
and here
you can make an ajax call to the server's websevice and it can return one of the well known web format (for e.g. json or XML). When the webservice call returns you can then "inject" the data in your html page with either javascript (dom manipulation) or using MVC helpers.
Here's one that could help..
http://www.asp.net/mvc/tutorials/older-versions/javascript/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript
You Can use jquery ajax which would call async action method(function). Data is returned the form of Json. You can write code to deserilize data and display it using jquery.
Create a Action method which would return JsonResult as viewresult as
public JsonResult GetJsonData()
{
return Json(new
{ testDataResult =TestDataResultObj.Data
JsonRequestBehavior
}, JsonRequestBehavior.AllowGet);
}
and write following jquery code:-
if (GetDataAsyc()) {
$.ajax({
type: "GET",
data: { testData: testDataResult },
url: url,// url of action method to be called asynch
dataType: "json",
cache: false,
traditional: true,
contentType: "application/json",
success: function (data) {
// on success assign testDataResult to messages //line
$("#MessagesLines").html(testDataResult .Html);
}
},
error: function () {
//Display error message
$("ErrorMsg").html("There was error whey trying to process your request")
}
});
}
Use ajax+PartialViews to update some page sections

using wcf instead of web service !

I'm using ajax in my website to call some information from a UserControl called NewsFeed.ascx which is found in the folder 'controls', my way is to make a web service page (in a folder called WebMethods) which contain a function in my case called GetRSSReader which returns a string format:
[WebMethod]
public string GetRSSReader()
{
Page page = new Page();
UserControl ctl =
(UserControl)page.LoadControl("~/Controls/NewsFeed.ascx");
page.Controls.Add(ctl);
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
then I call this page using Jquery (which I found it too heavy) to get the returned data as a JSON like this :
<div id="Content"></div>
<script type="text/javascript" defer="defer" src="../JAVA/Default.js"></script>
>
$(document).ready(Update);
function Requests()
{
$.ajax({
type: "POST",
url: "../WebMethods/Feed.asmx/GetRSSReader",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#Content').html(msg.d);
}
});
}
the Jquery.js and this page (default.js) founded in the folder Java
my question : can I not to use webService and instead using WCF !!! and how !?
What you refer to as "web services" is the old "ASMX Web Service" feature of .NET (sometimes known as ASP.NET Web Services).
WCF is the replacement for ASMX web services.
See https://stackoverflow.com/tags/wcf/info for some getting-started information.
If you're just returning JSON then I highly recommend you simply use an HttpHandler instead of some combination of WCF, SOAP, UserControls, and whatever else you're throwing in there. Here's a quick tutorial on the subject. You'd save yourself the overhead of page life-cycle stuff that you don't need. And returning the JSON is as simple as serializing your return values with the JavaScriptSerializer.

ASP.NET: UrlReferer has wrong value, interrogating in a static (webmethod) page called from jquery

Can anyone help? I am trying to interrogate the UrlReferer whcih should contain Google.com but it contains my current site. My web page is a standard HTM page and jquery calls a static method like so
[WebMethod]
public static void ProcessTracking(string jsonString)
Inside this method i do a standard lookup on Request.UrlReferrer like so
string referrerDomain = HttpContext.Current.Request.UrlReferrer.Host ;
But it always contains my current domain, this was a little suspect so i created a standard asp.net page and did the same and it works 100% without issue..
So it appears that when my htm page calls via jquery my webmethod (static) and interrogates the UrlReferrer it return ALWAYS my current site which is wrong.
Does anyone know a work around?
I even tried doing something in session_start etc in global.asax but no fix.
EDIT: How i am calling the page from jquery in html
$.ajax({
type: "POST",
url: "MyService.aspx/ProcessTracking",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
},
error: function(msg) {
alert(error);
}
});
That script is hosted on your page, right? In that case, the referrer will be your site.
If you want the referrer for the page itself, then you need to pass it as an argument with your Ajax call; it won't be present in the HTTP header.
You can read the referrer of the page from the document.referrer property.
Surely it should contain your current domain, as that is webpage doing the post?
If you want to retrieve the original callers page, you'll need to store that in the original webpage, before calling your ajax code, and then passing that through.
Resources called via AJAX requests will consider the calling page as the referrer, which is why your domain is showing up as the referrer.
You had the right idea to use the Global.asax, but try hooking in to the BeginRequest method:
void Application_BeginRequest(Object Sender, EventArgs e)
{
string referrerDomain = HttpContext.Current.Request.UrlReferrer.Host ;
}
This is working as intended. When you use AJAX to post, you are sending a request from your page (your domain!) to the target server.
One workaround would be to store the original referrer's host name in a javascript variable when constructing your page:
var referrerHost = '<%= HttpContext.Current.Request.UrlReferrer.Host %>';
Then package that into the jsonData variable you're sending to the ProcessTracking method in the ajax function's data parameter.

jQuery Postback with Webforms

We're redevloping a major section of our website and rather than use a 90k AJAX file I'd rather use a 19K jquery script.
I've seen the following articles;
Using jQuery for AJAX with ASP.NET
Webforms
jQuery autocomplete in ASP.NET webforms?
Autocomplete with ASP.Net MVC and
JQuery
The thing I don't get is how to do a postback to a specific method in either the code behind or another class.
I know in ASP.NET-MVC I can post back to a controller / action. How do I call a particular method in WebForms?
Something along the lines of; $.post("class and action", ( param:value}......
Any thoughts, code etc???
It is very easy to call specific methods in code-behind. Here is nice article with all the details by Dave.
Simply declare a method like this:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
This is all you need in jQuery:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status, xhr) {
// Do something interesting here.
}
});
Caveats:
WebMethod must be on a static method
Must stringify posted data if sending anything (i.e. JSON.stringify(yourDataObject)), will be deserialized according to method parameters
msg is the response, the return result from your method is in the property msg.d

Categories