Why Can WebMethod Access Session State Without EnableSessionState? - asp.net

I have a method on a page marked as a [WebMethod] that uses some session state as part of its operation. After I wrote this code, I suddenly had a flash of memory that you need to use EnableSessionState when you use session state in a [WebMethod] (e.g. see here: http://msdn.microsoft.com/en-us/library/byxd99hx.aspx). But it seems to be working fine. Why?
Sample code behind:
protected void Page_Load(object sender, EventArgs args) {
this.Session["variable"] = "hey there";
}
[System.Web.Services.WebMethod]
public static string GetSessionVariable() {
return (string)HttpContext.Current.Session["variable"];
}
Sample body html:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getSession() {
$.ajax({
type: 'POST',
url: 'Default.aspx/GetSessionVariable',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
document.getElementById("showSessionVariable").innerHTML = msg.d;
}
});
return false;
}
</script>
<form id="form1" runat="server">
<div id="showSessionVariable"></div>
<button onclick='return getSession()'>Get Session Variable</button>
</form>

On http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.enablesession(v=vs.90).aspx, you will see that this applies to XML Web services (i.e., classes derived from System.Web.Services.WebService).
[WebMethod(EnableSession=true)]
Because your page presumably extends System.Web.UI.Page, it is not necessary to explicitly enable the session. On http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx, you can see that EnableSessionState is enabled by default for Pages (which you probably already know).

http://forums.asp.net/t/1630792.aspx/1
Answer of gsndotnet:
You are right but whatever you are saying is applicable to a method in context of WebServices. We also use same WebMethod attribute on the methods of a WebService (.asmx). So in context of Web Services when we want to allow the access to Session we have to add EnableSession = true. Whereas in context of PageMethods they already have access to Session as they are defined inside a class that inherits from Page class.
Your msdn link means that you use web service, i.e. class derived from System.Web.Services.WebService.
In your code you add your method directly on page, so it has access to session.

Related

How to enable JSON support in Visual Studio (ASP.NET)?

How do I enable Visual Studio to recognize and manipulate JSON data in the code-behind files? (In other words, resolve json does not exist in the current context error). I'd like to be able to:
Retrieve JSON data from AJAX calls forwarded from the client side
Interpret, change, or create JSON objects with C#
Send a valid JSON response back to the client side and read it with Javascript
Be able to do all of the above irrespective of the runtime environment (i.e. I can't always assure that I will have a third party package installed in Visual Studio)
I've seen many answers, but most suggest to either (1) install a json package or (2) play with using directives. I've tried many variations of the latter with no luck.
What is the proper way to include JSON support in Visual Studio?
How does one properly retrieve (e.g. from a POST AJAX call), manipulate (e.g. change), and send back (i.e. respond to the client) JSON data in C#? Very basic, primitive examples would help!
ASP.Net Web Form has WebMethod. You can call those static method from client-side using Ajax.
ASPX
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DemoWebApplication.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<button type="button" onclick="postData();">Post Data</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
function postData() {
var user = { firstName: "John", lastName: "Doe" };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/default.aspx/postjson") %>',
data: "{user:" + JSON.stringify(user) + "}",
contentType: "application/json",
success: function (msg) {
console.log(msg.d);
}
});
}
</script>
</form>
</body>
</html>
Code Behind
using System.Web.Script.Serialization;
namespace DemoWebApplication
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string PostJson(User user)
{
user.FirstName += "Test";
user.LastName += "Test";
return new JavaScriptSerializer().Serialize(user);
}
}
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
What is the proper way to include JSON support in Visual Studio?
Visual Studio is nothing to do with sending and receiving JSON. If you want a proper way, you might want to consider using ASP.Net Web API.

How to return list of user defined data type using Ajax in ASP.NET?

I am trying to call a getData web method which will return a list of Destination table record (I am using ADO.NET Entity Framework Model) which contain cityID, country, city but I am getting a 500 internal server error.
if I make a new Destination object and adding it to a new list then there is no error. What to do please help me, I am a newbie.
console error
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
response text: "{"Message":"A circular reference was detected while serializing an object of type \u0027System.Data.Entity.DynamicProxies.Dest ......}"
Open image in new tab
.js
function getData() {
return $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Sandbox3.aspx/getData",
data: JSON.stringify({}),
dataType: "json",
});
}
$('button').on('click', function(e) {
e.preventDefault();
var promise = getData();
promise.success(showData);
promise.error(onError);
});
function onError(xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert(xhr.status);
alert(thrownError);
}
function showData(data) {
console.log(data.d);
}
.aspx.cs
public partial class Sandbox3 : System.Web.UI.Page
{
private static HotelDB db = new HotelDB();
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static List<Destination> getData()
{
return db.Destinations.ToList();
}
}
.aspx
<body>
<div>
<form runat="server">
<button id="box">Go</button>
</form>
</div>
<script src="scripts/jquery-1.8.3.js"></script>
<script src="scripts/ajaxtest.js"></script>
</body>
With entity framework you most likely have LazyLoading Enabled, disable that and try. What is most likely happening is, when you try to return the Desitniation object which EF made, it has a tblHotelDetails property, that is causing the issue. By disabling LazyLoading that property will not populate when you send your object back. If you need it populated, either create a custom class as you did, or you can disable LazyLoading and use the Include method to bring that property in, though i'm not sure if including it will lead to the same error.
If you want to see the actual error, get Fiddler, run that and then your site, when you get the 500 error, look at Fiddler and you will see the actual error.
I know this is a bit late, but maybe it will help someone else. For JSON, flatten and pay attention to any navigation properties (assuming an ORM like EntityFramework)...
In your case--the Destination navigation property... If it's a navigation property, you need to pull out the information (flatten)--e.g., Destination.DestinationName
public JsonResult getJson()
{
return this.Json(
new {
Result = (from obj in db.Product select new {Id = obj.Id, Name = obj.Name, obj.Category.Description})
}
, JsonRequestBehavior.AllowGet
);
}
Go take a look at the navigation property for Category... Chances are that you might have something similar to obj.Category, when you may actually intended to have obj.Category.Description or something similar (e.g., obj.Destination.DestinationName)... Navigation properties usually reference back to the parent again. JSON serializers don't do so well with understanding those "circular" references.
;-) I had the same issue a while back and I beat my head on the table when I realized what I had done.

how to call a c# webmethod on mouseover of linkbutton in asp.net?

Is it possible to call a c# webmethod on mouseover on Linkbutton ? what i want is to call a webmethod in which i am binding a repeater control with datatable. How?
in aspx:
<asp:LinkButton Text='<%#Eval("SNA")%>' ID="lnkpro1" runat="server"
CssClass="linkbutton" servicemethod="GetRecords"
OnClick="btn_Click1" CommandArgument='<%# Eval("Sets") %>'></asp:LinkButton>
in aspx.cs:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public void GetRecords(object sender, EventArgs e)
{
}
I am not getting the point that is how is it possible to call a webmethod on linkbutton mouseover. I have used a webmethod in textbox autocomplete extender but it has a propperty of calling a webmethod but is it so in this case also? Thank you.
Use ASP.NET AJAX Page Methods, like this:
[WebMethod]
public static List<Record> GetRecords()
{
// Go to database to get list of records
List<Record> listOfRecords = GetRecordsFromDatabase();
return listOfRecords;
}
I made up the Record class here. A list of something needs to be returned, so I made it up for the example's sake.
Note: ASP.NET AJAX Page Methods automatically JSON-encode their response, so there is no need for serialization in the page method if you are using JSON on the client-side.
Now you can call the ASP.NET AJAX Page Method, like this:
$(document).ready(function() {
$('.linkbutton').mouseover(function() {
$.ajax({
type: "POST",
url: "PageName.aspx/GetRecords",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// Do something with records returned here
// Use result.d to get to JSON data
}
});
});
});
You can do that using jQuery Ajax method to call a WebMethod:
Refer this for an ultimate example for Calling an ASP.NET C# WebMethod

How to Call Default.aspx.cs page method from Jquery Ajax?

I have a registration form(Default.aspx) which initially show's only 2 field's and a button (Name, email) when user click's on button Jquery makes an Ajax call to Default.aspx.cs function which query db to check for the user, and if it return no then the form expands itself adding registration fields.
I am not able to make a call to Defualt.aspx.cs
my Default.aspx code is :
<script type="text/javascript">
$(document).ready(function() {
$('#btnDownload').click(function() {
//$('#secondary').toggle(1000)
$.ajax({
type: "POST",
url: "Default.aspx/PassData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert('Failed');
}
});
</script>
And Default.aspx.cs is (for test purpose) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private static string PassData(string id)
{
return "Pass";
}
}
But every-time I run the code JS returns error :
Uncaught ReferenceError: com is not defined
POST http://localhost:2305/temp/Default.aspx/PassData 500 (Internal Server Error)
I check few posts but non of them had been answered/resolved.
Any kind of help would be highly appreciated.
Thanks in advance
You need to decorate the method with [WebMethod] attribute.
EDIT
You'll need to add a ScriptManager and use some ASP.NET ajax framework methods. I think what you want to do is impossible with the out-of-the-box functionality.
One option will be to create a HttpHandler that will handle those methods. If the request is a POST, you can find the page type from the url (there's a method in the framework but I can't remember which one, you'll need to investigate), create a new instance and check if the method has the WebMethod (or another attribute you like). If it does, you can call it using reflection and render the result.
EDIT
As #Antony Highsky pointed out, it's possible. I think the solution is to add the [WebMethod] attribute and make de method public (it's private in the example).
Use **[WebMethod]
[WebMethod]
private static string PassData(string id)
{
return "Pass";
}

ajax request Mootools to asp.net webforms

I am trying to post a request to the server but it wont hit when I use the debugger?
server:
public partial class _Default : System.Web.UI.Page
{
public string HitThis()
{
return "braza";
}
}
<script type="text/javascript">
var myRequest = new Request({
method: 'post',
url: '/Default.aspx/HitThis',
onSuccess: function () {
alert('good');
},
onFailure: function () {
alert('nope');
}
});
myRequest.send();
</script>
If you want to be able to call your HitThis method, you need to make that method, static, decorate it with the Web Method attribute and enable Page Methods on your ScriptManager
Example:
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
[WebMethod]
public static string HitThis()
{
return "Hello World";
}
You need to first understand how ASP.NET AJAX Script Services or PageMethod works! Page Methods has to be decorated with the WebMethod attribute and needs to be static.
[WebMethod]
public static string HitThis()
{
}
See this article that illustrates calling page method using jquery. You can adopt it with mootools. However, note that page methods needs content type to be JSON data and response will also be in JSON.
Perhaps you can write your own wiring logic in the ASP.NET page using Request.PathInfo if you want to use normal form posting. For example,
protected void Page_Load(object sender, EventArgs e)
{
if (this.Request.PathInfo == "HitThis")
{
HitThis();
}
}
In your method, you need to work with Response (HttpResponse) and after modifying the response, you need to end it (HttpResponse.End) so that normal page processing would not happen. If your method needs parameters then you have to pass them via form data and/or query string.

Resources