How to extract JSON data received in controller in a String variable - json

Could you please let me know how to extract JSON data received in a string variable in controller. Please see the attachment.Thanks.
$("#btn1").on("click", function () {
var i = new Array();
var j = 0;
$("#sl1").multiselect("getChecked").map(function () {
alert(this.value);
i.push(this.value);
//i[j] = this.value;
//j++;
}).get();
var postData = { values: i };
jQuery.ajaxSettings.traditional = true;
$.post('/TodoList/searchdata', postData, function (data) {
alert(data.Result);
});
//$.ajax({
// type: "POST",
// url: "/TodoList/searchdata",
// data: postData,
// success: function (data) {
// alert(data.Result);
// },
// dataType: "json",
// traditional: true
//});
});
Controller code:-
public void searchdata(String[] values)
{
//{
// JavaScriptSerializer js = new JavaScriptSerializer();
// List<String[][]> data=js.Deserialize<List<String[][]>>(i);
Console.WriteLine(values);
}

You can use Newtonsoft Json library https://www.nuget.org/packages/Newtonsoft.Json/
So As mentioned in the below link use it like below
string json = #"{ 'Email': 'james#example.com', 'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z', 'Roles': [
'User', 'Admin' ] }";
Account account = JsonConvert.DeserializeObject(json);
if you doesn't have model , just use like below
var model = JsonConvert.DeserializeObject(json);
the check the below link
http://www.newtonsoft.com/json/help/html/deserializeobject.htm

Try this
JavaScriptSerializer js = new JavaScriptSerializer();
var data=js.Deserialize<Dictionary<string, List<string>>>(i);

Use This Class :
public class JsonAttributeClass<T> where T:class ,new()
{
public static string EntityToJsonConvertor(T entity)
{
string json = JsonConvert.SerializeObject(entity);
return json;
}
public static T JsonToEntityConvertor(string json)
{
var entity = JsonConvert.DeserializeObject<T>(json);
return entity;
}
}

Related

Why do I get an empty parameter on the controller in my HttpPost method Ajax call?

I have a view that adds an Unordered list and list items to it at runtime, then I loop through to get the entered values, push the info to an object, and do the Ajax call to my method.
I always get an empty parameter on the controller, the console.log(assetWeighJsonDetail) shows what was entered, so I'm making sure I'm not passing and empty object (see the image below):
// Client side script:
var assetSerialNumber = "";
var weight = 0;
var assetWeighJsonDetail = [];
$(".ul-asset-weigh").each(function () {
var classNameSelected = this.id;
$("." + classNameSelected).each(function () {
assetSerialNumber = $(this).attr('id');
weight = $(this).val();
assetWeighJsonDetail.push({
OriginID: classNameSelected,
AssetSerialNumber: assetSerialNumber,
Weight: weight
});
});
});
console.log(assetWeighJsonDetail);
$.ajax({
url: "/AssetWeigh/SaveAssetWeigh",
data: JSON.stringify({assetWeighJsonDetail}),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
if (response) {
alert("success");
}
else {
alert("fail");
}
},
error: function (exception) {
}
});
// Console:
// Controller Method:
[HttpPost]
public ActionResult SaveAssetWeigh(List<AssetWeighJsonDetail> assetWeighJsonDetail)
{
bool success = false;
success = assetWeighJsonDetail != null && assetWeighJsonDetail.Count > 0;
return Json(success);
}
// Method's class List parameter:
public class AssetWeighJsonDetail
{
public int OriginID { get; set; }
public string AssetSerialNumber { get; set; }
public decimal Weight { get; set; }
}
You should try with $.post I have faced the same issue if using $.ajax and was not working and just switching to $.post made it work.
$.post( "/AssetWeigh/SaveAssetWeigh", parameters, function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
I'm on my phone and can't type all of it, I'll try to update later from my computer

Not Able To Parse Web Response Content

I'm trying to retrieve JSON from a URL and read it into my application. I am having an issue when reading the WebResponse. When the response is read, it comes back as only Symbols and is not properly formatted json.
How do I get a properly formatted JSON after streaming my WebResponse?
My Javascript is as follows:
function getJsonWM() {
//var stringedData = JSON.stringify(ajaxData);
$.ajax({
type: "GET",
url: '/Default/GetQuestionByHighestScore',
//data: JSON.stringify("{}"),
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: function (data) {
var label = $("#lblResults");
var json = JSON.stringify(data);
label.text(json);
//if (data.d.Pin == undefined) {
// alert("Error: " + data.d.ErrorMessage);
//} else {
// alert("Please record the following PIN: \r\n \r\n" + data.d.Pin);
//}
},
error: function (data) {
//alert("Error: " + data.d.ErrorMessage);
}
});
}
$(function() {
//$("#btnSubmit").click(getJson);
$("#btnSubmit").click(getJsonWM);
});
My controller is as follows:
public class DefaultController : Controller
{
private const string questionUrl = "https://api.stackexchange.com/2.1/questions?order=desc&sort=activity&site=stackoverflow";
public string GetQuestionByHighestScore()
{
List<Item> list = new List<Item>();
var json = GetJson(questionUrl);
var array = JsonConvert.DeserializeObject<Item>(json);
return list.OrderByDescending(x => x.Score).FirstOrDefault().ToString();
}
public string GetJson(string url)
{
var myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myWebRequest.Method = "GET";
myWebRequest.ContentType = "application/json";
var myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
string strResponse = String.Empty;
var encoding = Encoding.Default;
using (var reader = new StreamReader(myWebResponse.GetResponseStream(), encoding))
{
//JavaScriptSerializer js = new JavaScriptSerializer();
strResponse = reader.ReadToEnd();
}
return strResponse;
}
}
My strResponse object is as follows:
"‹\b\0\0\0\0\0\0µ\\\vÛ6¶þ+„\bÚ{G£%Q)‚ÜI“4\t6»iÓtw/”HÙšÑÕä™8Eÿû=‡”ly,y$·iÐ%òóññ¼éßi#ózñô[4|‰wÑe!›ÅÅ\"ßdMÚ¬*ÉEZ,ÿw±(ï\vY-žþ¶¨äzÓð&-‹ÅSÛv/›ZVשX<umæYžÝ¾i¶k¹x\nÝ—iÝÈJ\n`ËãX®›ëŠ7ÐÄØÅb]•IšÉë4çKì½jšuýÔ4Ó˺áñíeš/7Õe\\ææÏôêþß—7ëåóú™í°'Ëg60i½Îøöºà9’¼ÝþÄsÙÅ\"K‹Û–!ðSÜÊ;Y%Yy¯øák³²Yßn+EøûÅ\"­¯yQß«!?MxVË‹Å]*ï¯ãrS40i\a&¢:ìÞ\\,긬`|1¯›k7é]Úl¯…šªM=›:®ãBÏW¯ßd‡¡¶¤R¤Í™­Öô׬™Zih`®CŸfGSmiLµ·Æns\r؃Ï[#^ÉøVVFÝȸ1Š²1jÙMiðÂH\và\\ÄÒ(|Ô}`‘#®û{ÅòçŽ%Q,IË’ü]u'À’\0KÒ”„¤cIÊ[–¿_ìÁ˜oë_3ø’uY7ËJê\ažó/eaÀÞÔ«4iF‘é[¬‡L'p=Ë\n§\"3\bÆ‘y¹¬øo¸¦þhºŒ\a¡—D‚òÀŠBG¸’{^苘E2òe\v[ñ,²hÒ¸,žTÏ>üð$Âñ\aÞ4+m–“ÜÎÐ\\ï(§ ù!­©#v¼a ·MG`\rÄsÁŠ4fšÃFÜIc\rÝÊ*ï#\bs4 wµ565b¸*ïb“G\0„=*ßjZÒ£E´-Q´DÑ ½niûð[o›•’$u\t(nêq!Ø—¥>sN!m\fXÙÊ¿\\–å2“H\nøh\0'jYŒ¼æÅ««7âê­yµû¯÷ùÅ'35~i^_Õ/£[s½*›RËÊ/ˆºc€}¿ªÒšü$y6aíÌÌIá\0鈹gcÌG0qTXj²caÉ|¶°“g°oŒ0\b²PcÁÐÒÂÈ%#DôwµïbN÷¾Ô½¿ù–´ýû(«6ÑÖ#ÆÓ¬NøŒ˜“YkœÀºjÇ¥\\yãû¨f#oL¤IGDÂñ¤ð…å$qB=ϱœ€ZüBo–H“U&\vqS®øtíÜNÉìÓNÀ.˜‚¶ÏÂœZvh\ràÊòèl¹†4æýŠ7µc9¨7C&I§°ŠÆ=ß* É\fÕ0Gí,61ô­7ÑþB½è^ö0øà"
Looks like the server returns gzip encoded response. So make sure that you have set the AutomaticDecompression property when making your HTTP request:
public string GetJson(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
using (var response = (HttpWebResponse)request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string strResponse = reader.ReadToEnd();
return strResponse;
}
}
Also please get rid of those application/json content types. You are making a GET request which doesn't have a body - you are not sending any JSON. Also get rid of the contentType switch in your jQuery AJAX request (same reason).

knockout mapping of 3 dropdown lists using a JSON object containing 3 IList<CustomType>

Using Knockout I am trying to bind 3 dropdownlists with the data returned by an Ajax method calling a WebAPI.
The JSON data received is of Type "ReconDefMasters" where the calsses are defined as follows
public class MasterItem
{
public int MasterItemID { get; set; }
public string MasterItemName { get; set; }
}
public class ReconDefMasters
{
public IList<MasterItem> servFileFormat { get; set; }
public IList<MasterItem> mersRev { get; set; }
public IList<MasterItem> mersFileType { get; set; }
}
How to write the ko.mapping for this ?
I am able to achieve the result by returning IList, but then it requires 3 separate calls to the WebAPI- and trying to avoid this multiple calls by returning a composite object of 3 ILists.
I referred the below links , but not successful in modifying the logic for 3 dropdownlist together
http://jsfiddle.net/jearles/CGh9b/
Poblem with getting multidimensional array (object) observable in KnockoutJS
This is my code for single IList<> Method
var apipath = 'http://example.com';
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: false
});
function Master(data) {
var self = this;
self.FormatId = ko.observable(data.MasterItemID);
self.FormatName = ko.observable(data.MasterItemName);
}
var RuleDefVM = function (url) {
var self = this;
self.ServFileFormat = ko.observableArray();
self.selectedTemplate = ko.observable();
self.RuleDef = function () {
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response != "") {
$(response).each(function (index, element) {
self.ServFileFormat.push(new Master(element));
});
}
}
});
};
}
var urlRuleDef = apipath + '/api/RuleDef/';
var viewModelRuleDef = new RuleDefVM(urlRuleDef);
viewModelRuleDef.RuleDef();
function Master(data) {
var self = this;
self.FormatId = ko.observable(data.MasterItemID);
self.FormatName = ko.observable(data.MasterItemName);
}
selfDef.ServFileFormat = ko.observableArray();
selfDef.MERSRev = ko.observableArray();
selfDef.MERSFileType = ko.observableArray();
self.selectedTemplate1 = ko.observable();
self.selectedTemplate2 = ko.observable();
self.selectedTemplate3 = ko.observable();
jQuery.support.cors = true;
$.ajax({
url: url,
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function (response) {
if (response != "") {
$(response).each(function (index, element) {
$(element.servFileFormat).each(function (index,element) {
selfDef.ServFileFormat.push(new Master(element));
});
$(element.mersRev).each(function (index, element) {
selfDef.MERSRev.push(new Master(element));
});
$(element.mersFileType).each(function (index, element) {
selfDef.MERSFileType.push(new Master(element));
});
});
}
}
});
<select data-bind="options: ServFileFormat, value:selectedTemplate1, optionsText: 'FormatName' "class="dropdown"></select>
<select data-bind="options: MERSRev, value:selectedTemplate2, optionsText: 'FormatName' "class="dropdown"></select>
<select data-bind="options: MERSFileType, value:selectedTemplate3, optionsText: 'FormatName' "class="dropdown"></select>

JsonValue returned by MVC Web Api is empty in client side

I'm using MVC web Api for RESTful purpose. My controller methods return serialized Json object in string format. I've got some simple method like this:
public string Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name= folder.Name};
var jsSerializer = new JavaScriptSerializer();
return jsSerializer.Serialize(folder1);
}
I call Get, Put, Delete and Post methods in QUnit test like this and it works fine:
ajax: {
getData: function (url, data) {
return processRequest(url, data, "GET");
},
postData: function (url, data) {
return processRequest(url, JSON.stringify(data),"POST");
},
updateData: function (url, data) {
return processRequest(url, JSON.stringify(data),"UPDATE");
},
deleteData: function (url, data) {
return processRequest(url, JSON.stringify(data),"DELETE");
},
processRequest: function (url, data, type) {
return $.ajax({
type: type,
dataType: "json",
contentType: "application/json;charset=utf-8",
url: url,
data: data,
processData: true
});
}
},
I need to change return value from string to actual Json object because my client doesn't want serialized Json anymore. They need actual Json object. So I changed the method return type to JsonValue and parse the serialized Json object using JsonValue.Parse() method. When I trace my codes in server side, JsonValue object has proper values in its properties and looks fine but the returned JsonValue in client side has empty properties. here is changed method:
public JsonValue Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name= folder.Name};
var jsSerializer = new JavaScriptSerializer();
return JsonValue.Parse(jsSerializer.Serialize(folder1));
}
here is test result:
Expected:
{
"Id": "1",
"IsShared": true,
"Name": "abc"
}
Actual:
{
"Id": [],
"IsShared": [],
"Name": []
}
I appreciate any idea.
What I did to fix is adding Newtonsoft.Json.dll to my project and using Newtonsoft.Json.Linq.JToken instead of using System.Json.JsonValue. here is my method implementation:
public Newtonsoft.Json.Linq.JToken Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name = folder.Name};
var jsSerializer = new JavaScriptSerializer();
return Newtonsoft.Json.Linq.JObject.Parse(jsSerializer.Serialize(folder1));
}
and if you have an array of JSON, you need to parse like this:
public Newtonsoft.Json.Linq.JToken Put(IList<Folder> folders)
{
var folder1 = new Folder{Id="1", IsShared=true,Name = folder.Name};
var jsSerializer = new JavaScriptSerializer();
return Newtonsoft.Json.Linq.JArray.Parse(jsSerializer.Serialize(folders));
}

How to pass a JSON object to an action

I have the following jQuery code in a View in MVC3. I want to load a partial view (named OffshoreECore) in a div (#Form) depending on the JSON object passed in the success function. Here's the code:
var inputParamtrs = { 'HeadId': $('#ExpenseId').val(), MProjid': $('#MProjid').val() };
$.ajax({
type: "POST",
url: "/Expenses/Edit",
data: inputParamtrs,
success: function (json) {
('#Form').load('#Url.Action("OffShoreECore", *What comes here ?!?*)');
}
Thanks.
The second parameter of load() is the data which should be sent to the specified URL along with the request. To send your JSON string, try this:
success: function (json) {
$('#Form').load('#Url.Action("OffShoreECore")', json);
}
You example code is also missing a ' delimiter from the second key in inputParamtrs and the $ from the selector in success, but I guess they're just typos.
$.getJSON("/Expenses/Edit",
{
HeadId: $('#ExpenseId').val(),
MProjid: $('#MProjid').val()
},
function (data) {
elementForResult.innerHTML = data;
});
In Controller:
public JsonResult Edit(int HeadId, int MProjid)
{
...
var result = SerializeControl("~/Views/Expenses/Edit.cshtml", null);
return Json(result, JsonRequestBehavior.AllowGet);
}
private string SerializeControl(string controlPath, object model)
{
var control = new RazorView(ControllerContext, controlPath, null, false, null);
ViewData.Model = model;
var writer = new HtmlTextWriter(new StringWriter());
control.Render(new ViewContext(ControllerContext, control, ViewData, TempData, writer), writer);
string value = writer.InnerWriter.ToString();
return value;
}