How can I access session in a webmethod? - c#

Can i use session values inside a WebMethod?
I've tried using System.Web.Services.WebMethod(EnableSession = true) but i can't access Session parameter like in this example:
[System.Web.Services.WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod()]
public static String checaItem(String id)
{
return "zeta";
}
here's the JS who calls the webmethod:
$.ajax({
type: "POST",
url: 'Catalogo.aspx/checaItem',
data: "{ id : 'teste' }",
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});

You can use:
HttpContext.Current.Session
But it will be null unless you also specify EnableSession=true:
[System.Web.Services.WebMethod(EnableSession = true)]
public static String checaItem(String id)
{
return "zeta";
}

There are two ways to enable session for a Web Method:
1. [WebMethod(enableSession:true)]
2. [WebMethod(EnableSession = true)]
The first one with constructor argument enableSession:true doesn't work for me. The second one with EnableSession property works.

For enable session we have to use [WebMethod(enableSession:true)]
[WebMethod(EnableSession=true)]
public string saveName(string name)
{
List<string> li;
if (Session["Name"] == null)
{
Session["Name"] = name;
return "Data saved successfully.";
}
else
{
Session["Name"] = Session["Name"] + "," + name;
return "Data saved successfully.";
}
}
Now to retrive these names using session we can go like this
[WebMethod(EnableSession = true)]
public List<string> Display()
{
List<string> li1 = new List<string>();
if (Session["Name"] == null)
{
li1.Add("No record to display");
return li1;
}
else
{
string[] names = Session["Name"].ToString().Split(',');
foreach(string s in names)
{
li1.Add(s);
}
return li1;
}
}
so it will retrive all the names from the session and show.

You can try like this
[WebMethod]
public static void MyMethod(string ProductID, string Price, string Quantity, string Total)// Add new parameter Here
{
db_class Connstring = new db_class();
try
{
DataTable dt = (DataTable)HttpContext.Current.Session["aaa"];
if (dt == null)
{
DataTable dtable = new DataTable();
dtable.Clear();
dtable.Columns.Add("ProductID");// Add new parameter Here
dtable.Columns.Add("Price");
dtable.Columns.Add("Quantity");
dtable.Columns.Add("Total");
object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
dtable.Rows.Add(trow);
HttpContext.Current.Session["aaa"] = dtable;
}
else
{
object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
dt.Rows.Add(trow);
HttpContext.Current.Session["aaa"] = dt;
}
}
catch (Exception)
{
throw;
}
}

Take a look at you web.config if session is enabled. This post here might give more ideas.
https://stackoverflow.com/a/15711748/314373

In C#, on code behind page using web method,
[WebMethod(EnableSession = true)]
public static int checkActiveSession()
{
if (HttpContext.Current.Session["USERID"] == null)
{
return 0;
}
else
{
return 1;
}
}
And, in aspx page,
$.ajax({
type: "post",
url: "", // url here
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{ }',
crossDomain: true,
async: false,
success: function (data) {
returnValue = data.d;
if (returnValue == 1) {
}
else {
alert("Your session has expired");
window.location = "../Default.aspx";
}
},
error: function (request, status, error) {
returnValue = 0;
}
});

Related

How pass array object from Javascript to c# controller using ajax

I want to pass data from my cshtml file to my Controller. I want to pass an array. So I m build this code:
js:
function nextFunction() {
var listaDomande = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.pagina.domande));
var arrayRisposte = [];
//mi devo ricostruire il numero di domande che c'è in pagina, per ogni tipo devo verificarne i valori
for (i = 0; i < listaDomande.length; i++) {
var dom = listaDomande[i];
//alert(dom.idTipoDomanda);
if (dom.idTipoDomanda == 6) {
//DOMANDA CON OPTION BUTTON
//devo verificare per questo tipo di domande, quante opzioni erano possibili
//e recuperare solo il valore della opzione selezionata
for (n = 0; n < dom.opzioniDomanda.length; n++) {
//verifico quale è l'opzione selezionata dall'utente
var opzioniDomanda = dom.opzioniDomanda[n];
if (document.getElementById("oDomanda" + opzioniDomanda.ordinalId).checked) {
var value = document.getElementById("oDomanda" + opzioniDomanda.ordinalId).value;
alert(value);
var risposta = {
idDomanda: dom.rowId,
valore: value
};
arrayRisposte[i] = risposta;
break;
}
}
} else if (dom.idTipoDomanda == 3) {
//TEXT BOX
}
}
var valueText = document.getElementById("tDomanda");
alert(listaDomande.length);
$.ajax({
url: '/Questionario/nextPage',
data: JSON.stringify({ risposta: arrayRisposte}),
type: "GET",
success: function (data) {
//TODO: Add whatever if you want to pass a notification back
alert("RR Salvato");
},
error: function (error) {
//TODO: Add some code here for error handling or notifications
alert("Si è verificato un errore");
}
});
}
this is my controller method:
[HttpGet]
public void nextPage(RisposteUtente[] risposta)
{
try
{
Console.WriteLine("");
}
catch (Exception e)
{
Console.Write("");
}
}
This is my RispostaUtente object
public class RisposteUtente
{
public int idDomanda { set; get; }
public String valore { set; get; }
public RisposteUtente()
{
}
}
now if I try to execute js function, the call comes to the controller, but RisposteUtente[] is null.
Modify your AJAX call like this:
$.ajax({
url: '#Url.Action("nextPage", "Questionario")',
data: { "json": JSON.stringify(arrayRisposte)},
type: "GET",
success: function (data) {
//TODO: Add whatever if you want to pass a notification back
alert("RR Salvato");
},
error: function (error) {
//TODO: Add some code here for error handling or notifications
alert("Si è verificato un errore");
}
});
And your Controller method will look like:
using System.Web.Script.Serialization;
//using Newtonsoft.Json
[HttpGet]
public void nextPage(string json)
{
try
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Deserialize your JSON string if the struccture is an array
//var deserializedjson=JsonConvert.DeserializeObject<List<RisposteUtente>>(json);
//Get your variables here from AJAX call if the string is not an array
var idDomanda = jsondata["idDomanda"];
var valore =jsondata["valore"];
//Do something with your variables here
Console.WriteLine("");
}
catch (Exception e)
{
Console.Write("");
}
}

Post Json List of Object to webmethod in C#?

I am trying to post List of object (or array of object) to c# Webmethod. I am understanding how to receive as parameter in the method and convert into local List of object?.
for (var i = 0; i < usersInfo.length; i++) {
user = {
UserName : usersInfo[i].UserName,
Email : usersInfo[i].Email,
Status : status
};
users.push(user);
}
var results = "";
$('#lblError').val('');
if (users.length > 0) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'UserValidation.aspx/ShowResults',
data: "{'UsersInfo':'" + JSON.stringify(users) + "'}",
async: false,
success: function (data) {
results = data.d;
$('#lblError').val(results);
},
error: function (xhr, status, error) {
var exception = JSON.parse(xhr.responseText);
alert(exception.Message);
}
});
}
Code behind
[WebMethod]
public static void ShowResults(//Here how receive list object from javascript)
{
//convert parameter to List<UsersInfo>
}
public partial class UsersInfo
{
public string UserName { get; set; }
public string Email { get; set; }
public string Status { get; set; }
}
Try to replace this line
data: JSON.stringify({ UsersInfo: users}),
James you are the right track; you need to define the correct type for the ShowResults parameter so that the binding will work and bind the incoming json to your UsersInfo class.
Your UsersInfo class appears to be a simple POCO so should bind without any custom binding logic :
[WebMethod]
public static void ShowResults(List<UsersInfo> UsersInfo)
{
//No need to convert
}

Return JSON from MVC via AJAX

I've been using a hard coded JSON object:
var resuts = [{id: 1, Code: "Code A"}, {id: 2, Code: "Code B"}]
I'm then iterating this object calling the items by index and using .length:
for (var i = 0; i < resuts.length; i++) {
console.log('id:' + resuts[i].id + ' | ' + 'Code:' + resuts[i].Code}
Now I want to pull this data from the server so I created an object to handle the properties and have this action method:
public ActionResult GetResults()
{
string json = JsonConvert.SerializeObject(new
{
results = new List<Question>()
{
new Question { id = 1, Code = "Code A},
new Question { id = 1, Code = "Code B}
}
});
return Json(new { data = json }, JsonRequestBehavior.AllowGet);
}
I'm calling it with this AJAX:
function GetResultsJSON() {
$.ajax({
type: 'GET',
url: '/Home/GetResults/',
dataType: 'json',
traditional: true,
success: function (data) {
results = data;
},
error: function (data) {
alert('Error.');
}
})
};
Now my results object contains:
"{" results ":[{" id ":1," Code ":" Code A "},{" id ":1," Code ":" Code B "}]}"
Now I get JavaScript errors when trying to use the length property or call items by index. From what I have read up on, I think my original hard coded object is just an array, however, I have to work differently with the JSON that's returned from my controller.
Can anyone advise on either returning the array format that I was originally working with or the best way to handle the JSON format as it's returned here? I have tried things like
$.each(data, function(i, obj) {
alert(obj.name);
});
but this returns undefined. Any help would be great.
public JsonResult TestAjax(int leagueId)
{
var results = new List<BaseballViewModel>()
{
new BaseballViewModel{ DivisionId = 1},
new BaseballViewModel{ DivisionId = 2}
}.ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
$.ajax({
url: "/Home/TestAjax",
type: "GET",
data: { leagueId: 5 },
success: function (data) {
// alert(JSON.stringify(data)); show entire object in JSON format
$.each(data, function (i, obj) {
alert(obj.DivisionId);
});
}
});
Instead of:
$.each(data, function(i, obj) {
alert(obj.name);
});
why don't you try:
$.each(data.results, function(i, obj) {
alert(obj.name);
});
If you create a Model class that way :
[Serializable()]
public class MyResponse
{
public int Id {get; set;}
public string Code {get; set;}
}
And that you create a list of "MyResponse"
You will just have to do
return Json(new { data = listOfMyResponse}, JsonRequestBehavior.AllowGet);

Can't get data from GetJson method

Here is my code in Default.aspx:
$(function() {
var dataSource = {};
$("#MainTree,#SubTree").jstree({
"json_data": {
"ajax":{
type: "POST",
async: true,
url: "Default.aspx/GetJson",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg) {
dataSource = msg;
},
error: function(err) {
alert(err);
},
data: dataSource,
},
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
And here is GetJson method in Default.aspx.cs:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[System.Web.Services.WebMethod]
public static string GetJson()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
DataTable dtEmployee = new DataTable();
dtEmployee.Columns.Add("EmpId", typeof(int));
dtEmployee.Columns.Add("Name", typeof(string));
dtEmployee.Columns.Add("Address", typeof(string));
dtEmployee.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);
foreach (DataRow dr in dtEmployee.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtEmployee.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
EDIT:
This is the result when i check GetJson method respone:
{"d":"[{\"EmpId\":25,\"Name\":\"Rk\",\"Address\":\"Gurgaon\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":50,\"Name\":\"Sachin\",\"Address\":\"Noida\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":10,\"Name\":\"Nitin\",\"Address\":\"Noida\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":21,\"Name\":\"Aditya\",\"Address\":\"Meerut\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":100,\"Name\":\"Mohan\",\"Address\":\"Banglore\",\"Date\":\"\/Date(1372999726975)\/\"}]"}
And the result is nothing..It just appeared "..Loading" flashly and then it return blank page..please help me to show what's the problem here is..Thanks a lot.
It seems that you've not read the documentation properly so I would suggest you do that first.
When you use json_data plugin, you need to follow basic structure as shown below and could be found here, that means you need to provide Json data in below format:
{
"data" : "node_title",
// omit `attr` if not needed; the `attr` object gets passed to the jQuery `attr` function
"attr" : { "id" : "node_identificator", "some-other-attribute" : "attribute_value" },
// `state` and `children` are only used for NON-leaf nodes
"state" : "closed", // or "open", defaults to "closed"
"children" : [ /* an array of child nodes objects */ ]
}
Taking response structure into consideration, you need to have server side class as shown below:
public class Emp
{
public EmpAttribute attr { get; set; }
public string data { get; set; }
}
public class EmpAttribute
{
public string id;
public bool selected;
}
And your pagemethod should look alike below:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[System.Web.Services.WebMethod]
public static List<Emp> GetJson()
{
List<Emp> empTreeArray = new List<Emp>();
Emp emp1 = new Emp()
{
attr = new EmpAttribute(){ id= "25",selected=false},
data = "Nitin-Gurgaon"
};
Emp emp2 = new Emp()
{
attr = new EmpAttribute(){ id="50",selected=false},
data = "Sachin-Noida"
};
empTreeArray.Add(emp1);
empTreeArray.Add(emp2);
return empTreeArray;
}
Your clientside binding code should be like below:
$(function() {
var dataSource = {};
$("#demo1").jstree({
"json_data": {
"ajax":{
"type": "POST",
"url": "Default2.aspx/GetJson",
"contentType": "application/json; charset=utf-8",
"dataType": "json",
success: function(msg) {
return msg.d;
},
error: function(err) {
alert(err);
}
}
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
Notice return msg.d in Success function that is missing from your code.
More examples could be found here
Please go through documentation of any plugin you use next time.
type http://Default.aspx/GetJson directly in browser and check whether correct data is coming or not.
Other two locations where you can add debugging code is
success: function(msg) {
dataSource = msg;
},
error: function(err) {
alert(err);
}
add breakpoints and debug the javascript.
The response is encapsulated in a property called "d". Instead of datasource = msg you should have datasource = msg.d

WCF sending JSON, object in method always null

I want to send JSON data to my WCF Service, but in the Service there is my object always null. I have read so many articles but I can't solve my problem.
[WebInvoke(UriTemplate = "/POST/PersonPost", Method = "POST",BodyStyle=WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public Person InsertPerson(Person per)
{ Debug.WriteLine("InsertPerson");
if (per == null)
{
return new Person("2", "null");
}
Debug.WriteLine("POST:[PersonId = {0} PersonName = {1}]", per.Id, per.Name);
return new Person("1", "InsertPerson");
}
[DataContract]
public class Person
{
public Person(string id, string name)
{
this.id = id;
this.name = name;
}
[DataMember]
public string Id { get; set; }
[DataMember]
public string Name { get; set; }
public override string ToString()
{
var json = JsonConvert.SerializeObject(this);
return json.ToString();
}
}
and here my jQuery:
var person = {};
person.Id = "abc123";
person.Name = "aaaa";
var per = {};
per.per = person;
var param = JSON.stringify(per);
//param = "{"per":{"Id":"abc123","Name":"aaaa"}}"
$.support.cors = true;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
processData: false,
crossDomain: true,
url: "http://localhost:59291/Person/POST/PersonPost",
success: function (data) {
alert("Post erfolgreich: ");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Fehler Post: Status " + xhr.status + " AntwortText " + xhr.responseText);
}
});
What is there wrong? Why is my parameter per in the insertPerson method always null.
sorry my english, this work for me:
var LstPerson = new Array();
var person = {};
person.Id = 1
person.name = 'abc'
LstPerson.push(person)
var param = JSON.stringify(LstPerson);
send only [{"id": "1", "name": "abc"}] from JS, and WCF REST definition:
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
public Person InsertPerson(List<Person> per)
The reason this is not working is because the DataMembers are id and name and not Id and Name. You need to modify the following code:
person.Id = "abc123";
person.Name = "aaaa";
var per = {};
per.per = person;
to
person.id = "abc123";
person.name = "aaaa";
var per = {};
per.per = person;
Your web site is breaking the Same Origin Policy
Heres Ways to circumvent the same-origin policy
Your setting crossDomain to true, but this is only compatible with jsonp, read this
Try this:
var person = {};
person.id = "1";
person.name = "abc";
var param = JSON.stringify(person);
One of the reasons, you are receiving your request object as null because, the method is expecting an object of type Person. This in JSON is as follows according to your definition of Person.
{"id": "1", "name": "abc"}
This is because there is nothing like per inside Person.
Person person = New Person("1", "abc");
person.per //There is nothing defined as per inside person.

Categories

Resources