I have a 2D javascript array that is filled with user data and checked for valid data.
How do I go about getting that 2D array passed to my c# code behind page?
I am going to use the c# code to push it to a database after further processing.
From searching it seems like I need to get it to some sort of json to pass it to the c# code, but i'm at a complete loss on how to do that exactly and then what to do once I get it to the c# code.
Javascript array looks like this
[["Q458","","100","85"],
["Q459","TS","90","65"],
["Q460","","80","15"]]
There is a simple way to achieve this with the Newtonsoft.Json library (available for download via NuGet Package Manager - in Visual Studio click Tools -> Library Package Manager -> Manage NuGet Packages for this solution and search for "Json").
First you send this array to your code-behind - probably via AJAX request supplying your array as a parameter. To create a JSON string out of your array object, use the JSON-js (https://github.com/douglascrockford/JSON-js) library's stringify function as follows:
var jsonArrayString = JSON.stringify( your_array );
This string you will now send to your server and use Newtonsoft.Json to deserialize to an two dimensional list or array:
JsonConvert.DeserializeObject<List<List<string>>>( yourJsonString );
or
JsonConvert.DeserializeObject<string[,]>(yourJsonString );
To expand on MZetko's answer, here's a method you can use with jQuery and Json.Net.
First, you'll need to set up a way to send the js array to your c# code. You can use something like this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var items = [["Q458", "", "100", "85"], ["Q459", "TS", "90", "65"], ["Q460", "", "80", "15"]];
sendToDb(items);
function sendToDb(inArr) {
var inString = JSON.stringify(inArr);
$.ajax({
url: "/Handlers/some-generic-handler.ashx",
dataType: 'json',
type: 'post',
data: { myVar: inString },
success: function (data) {
if (data.success == true) {
alert("Here's the first element in the array: " + data.firstElement)
alert(data.message);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
Now, you'll need to build a handler that will answer the ajax request. This page will use Json.Net. The code will look something like this:
public class some_generic_handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string myVar = "";
if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.Form["myVar"])) { myVar = System.Web.HttpContext.Current.Request.Form["myVar"].Trim(); }
var myArr = JsonConvert.DeserializeObject<List<List<string>>>(myVar);
string firstElement = myArr[0][0];
string response = String.Format(#"{{ ""success"" : true, ""message"" : ""Cool! We're done."", ""firstElement"" : ""{0}"" }}", firstElement);
context.Response.ContentType = "application/json";
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Be sure to install Json.Net by PM> Install-Package Newtonsoft.Json, and then include the following reference:
using Newtonsoft.Json;
This demo will convert the js array to a string, send it to your handler page, the handler page will deserialize that string to a c# array, send back the first element in the array to the initial page, and then the initial page will alert the first element. In your application, you would use the handler page to insert data into your db table.
you can pass this from the client side to the server side using asp:HiddenField
Client
<asp:HiddenField runat="server" ID="myhf" Value="[['Q458','','100','85'],
['Q459','TS','90','65'],['Q460','','80','15']]"/>
Server
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var strArray = ser.Deserialize<string[][]>(myhf.Value);
now strArray is a 2D array you can loop through it and do you database insertion.
Related
I have seen a lot of posts that seem to somewhat address my situation but they all leave me a bit confused.
I have an object that I am POSTing to my Controller. I have the post coming to my controller okay by doing this:
$('#fileSubmit').click(function () {
var filesObj = [];
$('#fileList .files .fileName').each(function () {
var name = $(this).text();
filesObj.push({ 'name': name });
});
$.ajax({
type: "POST",
url: "/FileUpload/ImportCommit",
data: filesObj,
dataType: "json"
});
});
I want to then take that JSON object and put it into a list in my controller. So far here is what i have, but I have not done a lot of coding in C# and don't know what to do next.
[HttpPost]
public ActionResult ImportCommit(List<string> filenames)
{
}
I know my controller method's code is blank, but am not sure what to do next. Any help would be much appreciated. Thanks!
The post data you send via the data field of the ajax method needs to be name value pairs. Asp.Net will map them in the Request Params collection via their name. E.g. if you post an object like this,
{
fileNames: JSON.stringify(arFileNames)
};
It can then be accessed server side via,
string json = HttpContext.Current.Request.Params["fileNames"];
If your json looks something like this,
"{"filenames":["somefile","somefile2","somefile3"]}"
You could use newtonsoft JSON (JSON.Net) to convert it to a list of strings by creatong a class to represent it, like this,
public class JsonResultFileNames
{
[Newtonsoft.Json.JsonProperty(PropertyName = "filenames")]
public string[] FileNames { get; set; }
}
Then convert the json to JsonResultFileNames with,
JsonResultFileNames jsonResult = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonResultFileNames>(jsonStringHere);
Then you have a c# object representing your json data. Also you can get way more complex with this, but the important thing to note with JSON.Net, is it quite literally deserializes into a c# representation. E.g. if you want to deserialize straight to a string array, then there should only be an array of strings in your json (no object/field names etc).
E.g. where I work we have an api that returns results like this,
{
status: {
success: true;
},
customerdata {
id: {some-guid},
name: Some Customer Name
}
}
The problem with that, is my C# class needs to be composed of nested classes, e.g. I need a class to represent status and a class to represent customerdata. Things can get weird naming wise when doing that, I ended up with things like CustomerResponse, CustomerResponseStatus, CustomerResponseData, where CustomerResponseStatus and CustomerResponseData are exposed in CustomerRespnose, and I deserialize the json to the CustomerResponse type.
If your json is just an array of strings, you should be able to use string[] for the type passed into JsonConvert.Deserialize, which would not require you to make response classes to hold the data.
The trick was to modify my AJAX to POST like this:
$.ajax({
type: "POST",
url: "/dat/Controller",
data: JSON.stringify(filesObj),
contentType: "application/json",
traditional: true,
success: function (result) {
console.log("Success: " + result);
},
error: function (result) {
console.log("Error: " + result);
}
});
Changing dataType to contentType and adding traditional: true seemed to do the trick for me. The reason for this (I believe) is because the actual data that I was posting is technically not JSON. I added the traditional: true just to be on the safe side.
In my website, i'm declaring an array in javascript and insert them elements dynamically. So now, I want use that array from my C# code. I don't want use ajax to send that element to an web service... I just want use an C# event, like OnClick and access the array that was build in javascript.
I searched for an answer but I just found the oposite.
Thanks
The easiest way is AJAX call and i don't understand why you are avoiding that ?
Make an AJAX call from your button click.
look here a demo :
Ajax call is not calling to the server side and in httpfox shows error as "Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED)" in ajax post call
for example : covert your array to a json string and call a web client in your c# code. Here i have a button . on button click i want to send my GRIDVIEW data to c# method(web method).
you need to remember that while sending json data using stringfy() method,
in server side we need to define the parameter as object.
not any other format like string/int/bla bla.....
use Scripts/jquery-1.8.3.min.js
http://code.jquery.com/ui/1.10.3/jquery-ui.js
$('#btnResult').on('click', function () {
var mydata = [];
$("#<%=GridProjectDetails.ClientID %> tr").each(function () {
var myObject = new Object();
var id = $(this).find("input[name*='ID']").val();
var locationcode = $(this).find("input[name*='TextLocationCode']").val();
var Location = $(this).find("input[name*='TextLocation']").val();
myObject.id = id;
myObject.locationcode = locationcode;
myObject.Location = Location;
mydata.push(myObject);
});
var myString = JSON.stringify({ details: JSON.stringify(mydata) });
alert(myString);
var exportdata = myString;
$.ajax({
type: "POST",
url: "Default.aspx/ExportToExcel",
data: exportdata,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#Result").text(data.d);
},
error: function () { alert(arguments[2]); }
});
});
});
and server side method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ExportToExcel(object details)
{
return "Message : Success";
}
It's a kinda weird thing to do, but if you have to do it, you can do it by creating a form, inside the form have a hidden text field and call a function when submitting to update the value of this field.
The markup:
<form id="yourForm" method="post" >
<input type="text" name="hiddenFieldName" id="hiddenFieldName" hidden="hidden" />
</form>
The javascript:
void yourProcedure() {
var yourArray = ["Value1", "Value2", "Value3", "Value4"];
document.getElementById('hiddenFieldName').value = yourArray.join();
document.getElementById("yourForm").submit();
}
Then in the server, the form variable will contain "Value1,Value2,Value3,Value4".
I have a C#.net method as given below
public string jsonTest()
{
List<string> list = new List<string>();
list.Add("aa");
list.Add("bb");
list.Add("cc");
string output = JsonConvert.SerializeObject(list);
return output;
}
Here eventhough Im creating a Json object by using JsonConvert.SerializeObject I am getting a string (since return type is string).
Can I do like below by using a return type JsonResult (or somthing like that) something like what we can do in MVC?
return Json(new { data = list }, JsonRequestBehavior.AllowGet);
Is it possible to create a Json data in asp.net?
In client side I'm using an ajax call to get data from jsonTest().
$.ajax({
type: 'GET',
url: "test.aspx", //In test.aspx pageload calling jsonTest()
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert("In error");
}
});
When I'm giving dataType: 'json', it will go to error part (Since the ajax expects json data but it gets string). Thats why I want to parse it as a json object in server side.
If ASP.NET,
string output = JsonConvert.SerializeObject(list);
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(output);
Response.End();
There is nothing called a JSON object. The SerializeObject method returns a string because JSON is nothing more than a string value which follows specific rules.
To return JSON to the browser all you need to do is:
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonTest());
Response.End();
I'm going to assume you're trying to create a WebMethod for consumption by a JavaScript XHR call or similiar:
ASP.NET will auto-serialize to JSON for POST requests only (using ASMX or so called "Page Methods"). WCF and WebAPI do not require the POST method, but do require some configuration.
[WebMethod]
public static List<Task> TasksGet(string projectId) {
return MyNamespace.Tasks.GetForProject(projectId);
}
The result your JS call sees would be something like:
{"d": [{
"__type": "MyNamespace.Task",
"id": 1,
"description": "This is my first task"
}, {
"__type": "MyNamespace.Task",
"id": 2,
"description": "This is my second task"
}, {
....etc etc
}
]}
No need to mess around w/ the JsonSerializer class directly.
Also make sure your request headers are set correctly:
Content-Accept: application/json;charset=UTF8
Json is just string data. It is how that string is interpreted. So the fact that it is returning a string is correct. You mentioned ASP.Net. Are you using ASP.Net webforms and looking for a way to return that JSON to the front side?
Im trying to hook myself up to a smaller website im a member in.
It has some kind of chat board based on xml which i parse and do statistics on etc.
Now i want to be able to post short summarys using their own options for posting, handled by JavaScript here (cb is chatboard number):
function CB_Post() {
jQuery.ajaxSetup({ contentType: "application/x-www-form-urlencoded;charset=utf-8" });
//alert($("#message").val());
//$("#fm").serialize()
$.post("do.aspx?do=add", { message: $("#message").val(), cb: $("#cb").val() }, function (data) {
if (data == '') {
document.getElementById("message").value = '';
FC('message', iMaxChar);
} else {
alert(data);
}
}, "text");
My implemetaiton so far is:
public void PostData(string text)
{
var data = new NameValueCollection();
data.Add("message", (#text+#"\n"));
data.Add("cb", "0");
client.Headers["contentType"] = "application/x-www-form-urlencoded;charset=utf-8";
var result = client.UploadValues("/cb/do.aspx?do=add", data);
}
This works and the message get sent, but it ends up as a empty string in the chatroom, even if i just send "hey".
Am i missing some kind of formating or encodeing/decoding here?
Well you would think there would be some security that would be preventing you from posting like that so that might be the issue.
However I suspect that do.aspx is expecting JSON data not a NameValueCollection object.
If you take a look at this post it seems the recommended route is to use a Dictionary<string, string>() and then serialize it with the JavaScriptSerializer().serialize.
I am using the web kit browsers local database to temporarily store some data and when I want to access it I create an object
function patientSelectHandler(transaction, results) {
var row = results.rows.item(0);
var patient = new Object();
patient.name = row['name']
patient.dob = row['dob']
patient.gender = row['gender']
}
Is there a way to access this object from code behind, without having to populate textfields/labels/dropdowns and then get the values from there?
example as it is now:
function patientSelectHandler(transaction, results) {
var row = results.rows.item(0);
var patient = new Object();
patient.name = row['name']
patient.dob = row['dob']
patient.gender = row['gender']
$('#txtPatientName').val(patient.name);
$('#txtDOB').val(patient.dob);
$('#ddlGender').val(patient.gender);
}
edit:
Updating my example a bit:
var patientString = JSON.stringify(patient);
var inputField = $("<input type='text' name='hiddenField" + i + "' id='hiddenField" + i + "'></input>");
$('#Patients').append(inputField);
$('#hiddenField' + i).val(patientString);
and then a loop in the code behind
for (int i = 0; i <= count; i++)
{
string n = String.Format("{0}", Request.Form["hiddenField" + i]).ToString();
JObject o = JObject.Parse(n);
string name = (string)o["name"];
//now I can get all values into variables and use them when calling the web service
}
You don't need to set it to textfields for any reason...
I would probably do something like
var patientString = JSON.stringify(patient);
$('#myHiddenInput').val(patientString);
Otherwise, depending on the flow of your application, you can post that object in string form to the server using AJAX.
Then, you will have to use a method to parse that string back into object formation. I'm not to familiar with c# but i'm sure it would be easy to find or write such a method.
If you have many fields to send, you can JSON encode everything and put it into a single multiline text field (textarea). Then you can easily decode it on the server.
Keep in mind -
When your server code runs, it builds up a page object that it then uses to generate html to send to the browser. Once the html is generated that page object is destroyed. By the time the browser shows your page, your server resources don't exist any more.
When the browser submits a request for a page, it destroys the DOM for whatever page it's showing. So by the time your server starts, your javascript doesn't exist any more.
Thus, the two systems are normally completely separate. You can get around this by passing ajax json messages between client and server.
I would use AJAX post to store your JSON object on the server.
var str = JSON.stringify(...);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/validate",
data: str,
error: function(XMLHttpRequest, textStatus, errorThrown) {
...
},
success: ajaxCallback,
dataType: "json"
});
And on the server
[WebMethod]
public static string validate(Dictionary<string, object> patient)
{
...
//return your JSON response
}
And then just iterate through Dictionary object on the server (key - object parameter, value - it's value).