jQuery Postback with Webforms - c#

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

Related

prevent returned json being wrapped in { d: [duplicate]

I've created a simple C# asp.net web service function which returns a string message
and I am calling it from page using jquery ajax.
C#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
return DateTime.Now.ToString();
}
JS:
$(document).ready(function() {
//alert("ready");
$.ajax({
type: "POST",
contentType: "application/json; chatset=utf-8",
url: "WebService2.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg) {
//alert(msg); //doesnt works
alert(msg.d);
}
});
});
My question is that why does alert(msg); doesnt works
It's a security hardening mechanism.
Essentially, it helps protecting against CSRF type of attacks where the attacker reads a JavaScript array (downloaded as Json) from a victim website. They can do that by overriding JavaScript's Array type. d causes the returned Json to not be an array and thus turns Array overriding useless for the attacker.
See this great blog post: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
ASP.NET and WCF JSON service endpoints actually wrap their JSON in an
object with the “d” property to circumvent a subtle potential
security flaw when using JSON
Phil Haack's post on this: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
This was introduced from ASP.NET3.5. If you want msg to work in both frameworks before and after 3.5, just try this small hack.
var data = msg.hasOwnProperty("d") ? msg.d : msg;
Courtesy Dave Ward: Never worry about ASP.NET AJAX’s .d again

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

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

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.

jQuery does not load response

I normally use ASP.NET MVC 2, but there were some problems with it, so I began to work with ASP.NET MVC 2 + jQuery and everything works. But there is one problem, jQuery doesn't load my reponse. On the ASP.NET MVC side I'm redering a partial view and I also get the respone on the client, but nothing is rendered. How can I solve this?
Here is the jquery code:
function addCredential(state, id) {
var daten = getJson(state, id);
$.ajax(
{
type: "POST",
url: "/Account/SetCredential/",
data: daten,
dataType: "json",
success: function(partialView) {
$('#Credentials').replaceWith(partialView);
location.reload();
}
});
return true;
};
function getJson(state,id) {
var username = $('#username').val();
return {"username": username, "credential_id": id , "state": state };
};
The problem looks like location.reload();
That's reloading your page after you update it with AJAX, effectively returning it's state back to the way it was before you inserted the content with .replaceWith()
UPDATE: looks like you're using dataType: "json" and inserting that into the DOM? That's probably also a problem. If the view is being returned as HTML, you should replace that with dataType: "html"
#Konrad, try using the JSON2 library (http://www.json.org/js.html) to alert the "partialView" object in your success function to see what you're getting prior to reloading the page. Also, make sure $('#Credentials') is returning an object. When I run into issues when trying to select elements on the page, I usually check the length value of the jQuery object that is returned. If length = 0, then you're not getting the element.
UPDATE:
Also, if you're trying to inject HTML into $('#Credentials'), then partialView may not be the correct format. The success function accepts an object argument which comes from parsing of the responseText of the web method you called to get what you call partialView.
UPDATE:
Check http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/ for more info using $.ajax. Lots of great info on this blog.
UPDATE:
This is how I use JSON lib to view the data that is returned.
alert(JSON.stringify(partialView));

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.

Categories