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

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("");
}
}

Related

Pass 2 different data types with jQuery to HttpHandler

Is it possible to pass 2 data types to the HttpHandler in a Webhandler
$.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType:false,
processData: false,
data: {
data: newData,
pathname:"~/pathname/"
},
success: function (result) {
alert('success');
},
error: function () {
alert("There was error uploading files!");
}
});
The RequestPayload in the POST is [object object], is there documentation on how I can parse that object?
Hi Create a new model with all the props including the pathname prop
public class HandlerModel
{
public datatype dataprop1 {get;set;}
public datatype dataprop2 {get;set;}
public datatype dataprop3 {get;set;}
public datatype dataprop4 {get;set;}
public string pathname {get;set;}
}
then in your ashx file
public class QueryStringHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
//set the content type, you can either return plain text, html text, or json or other type
context.Response.ContentType = "text/plain";
//deserialize the object
UserInfo objUser = Deserialize<HandlerModel>(context);
//now we print out the value, we check if it is null or not
if (objUser != null) {
context.Response.Write("Go the Objects");
} else {
context.Response.Write("Sorry something goes wrong.");
}
}
public T Deserialize<T>(HttpContext context) {
//read the json string
string jsonData = new StreamReader(context.Request.InputStream).ReadToEnd();
//cast to specified objectType
var obj = (T)new JavaScriptSerializer().Deserialize<T>(jsonData);
//return the object
return obj;
}
}

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
}

AngularJS object is not properly converted into a ViewModel .NET

I have an AngularJS directive which returns me an array with some values, like this below:
The AngularJS code I'm using to generate this object like above is:
//--------------------------
// service...
service.getSelectedOptions = function() {
var options = [];
for (var I = 0; I < service.optionList.length; ++I) {
var availableOption = service.optionList[I];
if (availableOption.selecionado !== '') {
options.push(availableOption);
}
}
return opcoes;
};
//--------------------------
// controller...
var options = [];
var list = OptionsService.getSelectedOptions();
for (var I = 0; I < list.length; ++I) {
var option = list[I];
options.push({ Handle: option.Handle, Selecionado: option.Selecionado });
}
console.log(options);
// Sending the values to backend...
doPost('..../SaveOptions', { options: options }, function (result) { });
Ok, I created a ViewModel class to receive those objects into my controller.
public class OptionsViewModel {
public int Handle { get; set; }
public string Selecionado { get; set; }
}
My controller is declared like this below:
public JsonResult SaveOptions(OptionsViewModel[] options) {
//...
}
The problem is: if I chose 4 options, the array in the backend has 4 options, but the values are not binded to the objects.
Why that? Anyone knows why? Thanks!!
The solution was modify two parameters in the AJAX call:
Set contentType: "application/json";
Use JSON.stringify(parameters) to the parameters.
Thanks!

Deserialize Json string from MVC action to C# Class

I have an Ajax call (for a HighChartsDB chart) in a WebForm application that calls a webservice, which uses a WebRequest to call an MVC action in another application which returns a JsonResult.
I manage to pass the data back to the ajax call but the data I get back is not parsed as a json object but just a string.
My class:
public class CategoryDataViewModel
{
public string name { get; set; }
public List<int> data { get; set; }
public double pointStart { get; set; }
public int pointInterval { get { return 86400000; } }
}
My ajax function called by the highcharts:
function getBugs(mileId) {
var results;
$.ajax({
type: 'GET',
url: 'Services/WebService.svc/GetData',
contentType: "application/json; charset=utf-8",
async: false,
data: { "mileId": parseInt(mileId) },
dataType: "json",
success: function (data) {
console.log(data);
results = data;
}
});
return results;
}
And finally my WebService
public class WebService : IWebService
{
public string GetData(int mileId)
{
string url = "http://localhost:63418/Home/GetWoWData?mileId=" + mileId;
WebRequest wr = WebRequest.Create(url);
using (var response= (HttpWebResponse)wr.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
return objText;
}
}
}
}
With this when I console.log(data) on the ajax call I get:
[{\"name\":\"Sedan\",\"data\":[30,30,30,30,35],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Low\",\"data\":[800,800,800,826,1694],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Medium\",\"data\":[180,180,180,186,317],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"High\",\"data\":[29,29,29,34,73],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Truck\",\"data\":[6,6,6,6,13],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"SUV\",\"data\":[-172,-172,-172,-179,-239],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Convertible\",\"data\":[0,0,0,0,-404],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Limo\",\"data\":[-7,-7,-7,-8,-214],\"pointStart\":1307836800000,\"pointInterval\":86400000}]
I can't seem to manage to pass back into a proper Json object. I tried converting it back to my CategoryDataViewModel with this in my webservice:
var myojb = new CategoryDataViewModel ();
using (var response = (HttpWebResponse)wr.GetResponse())
{
using (var reader = new StreamReader(response .GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
myojb = (CategoryDataViewModel )js.Deserialize(objText, typeof(CategoryDataViewModel ));
}
}
return myojb;
But then I get Type 'Test.CategoryDataViewModel' is not supported for deserialization of an array.
Change:
myojb = (CategoryDataViewModel )js.Deserialize(objText, typeof(CategoryDataViewModel ));
to:
myojb = (List<CategoryDataViewModel> )js.Deserialize(objText, typeof(List<CategoryDataViewModel>));
and you should be fine. The array will de-serialize to a list no problem.
I've seen a similar thing before, I think you might need to change myObj to a list.
List<CategoryDataViewModel> myObjs = new List<CategoryDataViewModel>();
...
myObjs = js.Deserialize<List<CategoryDataViewModel>>(objText);

How can I access session in a webmethod?

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;
}
});

Categories

Resources