The below code is returning [object Object] not a string. How can I get it to return the correct string representation? I am using ASP.NET MVC4 C#.
public JsonResult Names(string name)
{
var a = db.NamesToGet.Select(e => new
{
name = e.Names
});
return Json(a, JsonRequestBehavior.AllowGet);
}
try
var a = db.NamesToGet.Select(e=>e.Names);
Access it with data.name or substitute data to your json variable name.
$.get("/Controller/GetName", function(data) {
alert(data.name);
//or alert(data[0].name);
});
Related
I have a controller method accepting two parameters. This method is used to retrieve a particular row of data corresponding to the ID which is passed via parameter. I have to send the another parameter in the return type value along with the retrieved data. How can I do that?
public JsonResult GetById(int? id, string message)
{
var data = (from z in db.ProdModels
where z.FirmId == id
select z).ToList();
//data.Add();
return Json(data, JsonRequestBehavior.AllowGet);
}
I have to return string message with the JSON returned data. Is it possible? Is there any way of returning the string along with the Json data?
Try this
return new JsonResult( new {data=data, message=message});
or I usually prefer
public ActionResult GetById(int? id, string message)
{
if(id==null) return BadRequest();
var data = (from z in db.ProdModels
where z.FirmId == id
select z).ToList();
return Ok( new {data=data, message=message} );
}
or if you using an old Mvc version
var result= new
{
Message = message,
Data = data
};
return Json(result, JsonRequestBehavior.AllowGet);
I'm trying to get JSON out of a webforms.cs page to .aspx page. It's relatively easy to do with JSONResult in MVC but it seems to be a pain with webforms.
So I have [WebMethod] function in my cs file like below.
This method is returning really weird json.
Fiddler's raw result looks like below.
{"d":"[[{\"name\":\"Label1\",\"y\":28....
Is there something like JsonResult for webforms? I guess since method return is of type string it's messing up the result and I don't know why it's coming up as array inside array and with name d.
I need this in [{name: "Label1", "y":28},{...] format.
How do i get it in this format?
[WebMethod]
public static string GetData()
{
JavaScriptSerializer json = new JavaScriptSerializer();
var myTable= DataTable.AsEnumerable().Where(x => x.Field<int>(1) == 2018)
.Select(x => new[]
{
new { name = "LABEl 1", y = x[2] },
new { name = "Label 2", y = x[3] },
});
String export= json.Serialize(myTable);
return export;
}
You could easily convert it back to json inside success method of your Ajax call using
var obj = JSON.parse(response.d);
I am intentionally trying NOT to use a binding in the controller parameter, so I have a controller that looks like:
[HttpPost]
public ActionResult UntypedForm(String serializedformdata)
{
//// ...
}
When I post serialized JSON form elements to the controller with the below code:
var formelements = $('#form').serializeArray();
$.post(url, formelements, function (data) {
}, "json").error(function () {
alert("Error posting to " + url);
});
I get a NULL value for String serializedformdata on my controller. However, when I replace String serializedformdata with a strongly-typed object, binding works properly as expected.
The whole point of my controller is generic JSON posts, where I will create a BSON document to place into a Mongo database. SO....I intentionally DO NOT want model binding and I want the serialized string as pamameter. Why is my serializedformdata string null when I post?
Note - I also tried to bind to Dictionary with
public ActionResult UntypedForm(Dictionary<string,string> serializedformdata)
{
//// ...
}
but serializedformdata is still null.
The function serializeArray creates a Javascript object with the form's key/value pairs. You don't want that, you want a single key/value with serializedformdata = (JSON string). Ie, like this;
var formelements = { serializedformdata: JSON.stringify($('#form').serializeArray()) };
This passes the raw JSON string to the controller's parameter. You can use the JavaScriptSerializer to get the object on the server:
var obj = (List<Dictionary<string,string>>)new JavaScriptSerializer().Deserialize(serializedformdata, typeof(List<Dictionary<string,string>>));
Dictionary<string,string> dict = obj.First();
string someval = dict["somekey"];
I'm trying to pass a couple of arguments to my JSON callback, however the string[] argument remains null. How do I need to pass the string array from javascript to get this working?
Javscript function:
function jsonCallback(jsonCallbackID, argumentsArray) {
var argumentValues = [];
for (var i = 0; i < argumentsArray.length; i++) {
argumentValues.push('' + $("#" + argumentsArray[i]).val());
}
// build request
var url = encodeURI("/DataEntry/JsonCallback/");
var data = ({ jsonCallbackID: jsonCallbackID, jsonCallbackValues: argumentValues, rndvalue: Math.floor(Math.random() * 10000000001) });
// fire request
$.getJSON(url, data, function (data) {});
The actual callback C# function:
public JsonResult JsonCallback(int jsonCallbackID, string[] jsonCallbackValues)
{ }
This function does get called however, argument 'jsonCallbackValues' is null.
EDIT
To get this working I did the following:
var data = ({ jsonCallbackID: jsonCallbackID, jsonCallbackValues: argumentValues.toString(), rndvalue: Math.floor(Math.random() * 10000000001) });
And split the jsonCallbackValues string at "," to get the resulting array.
You can give a try to JSON API ...
var data = {
jsonCallbackID:jsonCallbackID,
jsonCallbackValues: JSON.stringify(argumentValues),
rndvalue: Math.floor(Math.random() * 10000000001)
};
// your
$.getJSON(url, data, function (data) {});
JSON is a serialized language, so you can't put objects inside.
You should build your array in JSON format:
jsonCallbackValues : ["value1", "value2"...]
Try like this
var data = ({ jsonCallbackID: jsonCallbackID, jsonCallbackValues: $.toJSON(argumentValues), rndvalue: Math.floor(Math.random() * 10000000001) });
I have used a JSON jQuery plugin from http://code.google.com/p/jquery-json/
In the controller method change it to
string jsonCallbackValuesArray
Then use
JavaScriptSerializer orJSON.Net
to convert the JSON string into String []
I have an asp.net-mvc website and i am reading in Json string from a Database. Here is the following json in a DB. It could look like this:
{"description": "Test", "contacts": ["joe#gmail.com", "bill#yahoo.com"], "enabled": true}
or this:
{"description": "Test", "contacts": "joe#gmail.com, bill#yahoo.com", "enabled": true}
so as you can see, the contacts field is either:
a string (with items separated by commas)
an array of strings.
I want to convert to this class:
public class MyJob
{
public string description;
public string[] contacts;
public string enabled;
}
when i try to assign just to a string (changing the above to this: public string contacts;
) using the JavascriptSerializer():
var serializer = new JavaScriptSerializer();
string contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts;
I get this error in the cases where its an array: Type 'System.String' is not supported for deserialization of an array.
what is the best way to go about deserializing this to handle the case of:
a string
an array of strings.
for the contact field. I am happy to put any conditional logic needed . .
I tried this:
var contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts;
if (contacts is string)
{
jobInfo.contacts = contacts;
}
else
{
jobInfo.contacts = String.Join("; ", contacts );
}
but that didn't seem to fix as i am still getting the error above when its an array
try
var contacts = (new JavaScriptSerializer().DeserializeObject(theAboveJsonString) as Dictionary<string, object>)["contacts"];
if (contacts is object[])
{
jobInfo.contacts = String.Join("; ", contacts as object[]);
}
else
{
jobInfo.contacts = contacts.ToString();
}
For reference see MSDN and here.
You may be interested in some details here: JSON.net - field is either string or List<string>
If you're willing to use Json.NET, have this function:
public string[] getAsArray(JToken token)
{
if (token.HasValues)
{
return token.Select(m => string(m)).ToArray();
}
else
{
return ((string)token).Split(",").Select(s => s.Trim()).ToArray();
}
}
Then usage:
var json = "...";
JObject o = JObject.Parse(json);
string[] contacts = getAsArray(o["contacts"]);
For either JSON the result should be the same.
Try to deserialize contacts into a string array instead of a plain string:
string[] contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts;
if the JSON variable is holding a plain string, use:
string[] contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts.Split(',');