Display json data as table in view of MVC - c#

i am working in MVC 4 application. i am trying to bind the json data to table in view that reflects as a table view in the View Page.
here is my controller code....
if (reportType == "Report")
{
result = client.GetApiRequest("api/TurnoverReport/get?packageID=" + Convert.ToInt32(packageID)).Result;
}
here in result is a datatable that holds the output data as a datatable.
to pass the table to View i am serializing the table as :
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 = new Dictionary<string, object>();
row.Add("text", result);
rows.Add(row);
var test = JsonConvert.SerializeObject(rows, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return Json(serializer.Serialize(test), JsonRequestBehavior.AllowGet);
here I'm using the jsonconvert because of i am having this error message like
A circular reference was detected while serializing an object of type 'System.Globalization.CultureInfo'.
so, this json return the data as :
i have tried like to display in View but i couldn't get the expected result..
here is the View code that;
function GenerateReport(packageID) {
var repType = '#ViewBag.ReportType';
$.ajax({
url: '/turnover/GetTurnover' + repType,//?packageID=' + packageID,
data: { "packageID": packageID },
cache: false,
type: 'POST',
datatype: 'JSON',
success: function (response) {
debugger;

you can try this one in your javascript method
function GenerateReport(packageID) {
var repType = '#ViewBag.ReportType';
$.ajax({
method: "POST",
url: '/turnover/GetTurnover' + repType,//?packageID=' + packageID,
data: '{"packageID":' + packageID + '}',
contentType: "application/json; charset=utf-8",
success: function (data) {
//loop to data.text
$.each(data.text, function( index, row ) {
console.log(row);
});
}

Related

Ajax send model to controller as JSON

I have a model I am trying to pass in from my view to my controller via an Ajax call which stringifies both the model and another string of data like this:
SetBinConfig: function (model, range) {
var _model = JSON.stringify(model);
var rangeSplit = range.split(/[ -]+/);
var _rangeSplit = JSON.stringify(rangeSplit);
var data = "model=" +_model + "&rangeSplit=" + _rangeSplit;
$.ajax({
url: '/IdentifiConfig/DefaultConfiguration/SetBinConfiguration',
type: 'POST',
data: "{'data' : '" + data + "'}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
if (data.error == 1) {
cc.jqUtils.openDialog(data.ErrorDescription, 'Error', 'OK', null, null, null);
}
},
error: function (x, h, r) {
console.log(x, h, r);
}
});
},
Which is then received by this method:
public ActionResult SetBinConfiguration(string data)
{
string range = data.Split(new string[] { "&rangeSplit=" }, StringSplitOptions.RemoveEmptyEntries)[1];
string tempModelData = data.Split(new string[] {"&rangeSplit="}, StringSplitOptions.RemoveEmptyEntries)[0];
string modelData = tempModelData.Replace("model=", "");
DefaultConfigurationModel model = new JavaScriptSerializer().Deserialize<DefaultConfigurationModel>(modelData);
string[] rangeSplit = Regex.Split(range, " - ");
foreach (IdentifiBINConfiguration ibc in model.IdentifiBINConfigs)
{
if (ibc.LowerRange == rangeSplit[0] && ibc.UpperRange == rangeSplit[1])
{
model.IdentifiBINConfiguration = ibc;
return Json(new { error = 0 });
}
}
return Json(new { error = 1 });
}
However, I get this error:
The value "System.Collections.Generic.Dictionary`2[System.String,System.Object]" is not of type "IdentifiMessenger.Implementations.Identifi.Object.IdentifiBINConfiguration" and cannot be used in this generic collection. Parameter name: value
And I don't know what that means at all. I know what the Dictionary is, but why can I not just deserialize this object? I followed other answers right here on SO and I don't understand why this isn't working.
Edit:
Model is quite literally my model, sent from my JS like this:
IdentifiConfig.SetBinConfig(#Html.Raw(Json.Encode(Model)), $('#BinRangesHidden').val());
And range is just a value from a hidden. I'm not posting back my model because I just need to modify one value and then have the page pull that modified value down later.
You still have to serialize your data.
data: JSON.stringify(data),
Then in your controller, your object should auto-parse:
public ActionResult SetBinConfiguration(MyData data)
Alternatively, you can parse it manually:
public ActionResult SetBinConfiguration(string data)
{
MyData resumeDto = JsonConvert.DeserializeObject<MyData>(data);
...

ajax call serialize and deserialize data

I have the following ajax call:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/LoadCount.aspx/GetCounts",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(data) {
var myObj = JSON.parse(data.d);
alert(myObj.length);
for (var i = 0; i < myObj.length; i++) {
alert(myObj[0]);
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I am getting undefined when I alert the length
Here's my Method in my LoadCount.aspx
[WebMethod]
public static string ObtenerContador()
{
List<MenuItem> menu =(List<MenuItem>)HttpContext.Current.Session["MenuItems"];
Dictionary<string, int> dic = new Dictionary<string, int>();
foreach (MenuItemAMostrar item in menu)
{
dic.Add(item.ControlID,1);
};
return new JavaScriptSerializer().Serialize(dic); //or any other suggested serialization method
}
this is what I am getting in the success function:
{"MenuCLESAAsignar":1,"MenuOCGestores":1,"MenuOcAAutorizar":1,"MenuOcAAutorizarBanco":1,"MenuOCGestoresObservadas":1,"MenuCLESActivos":1,"MenuParametros":1,"MenuCLESConAddendaAAprobarSup":1,"MenuPendienteAprobacion":1,"MenuConsultaCLES":1}
The question is, how do I deserialize that dictionary in my ajax success function?
Once deserialized, how do I populate it, obtaining the data?
thanks!
As somebody else mentioned, you just use JSON.parse() to parse the data.
From there it just creates an object, and you can access the data with ..
Like so:
http://jsfiddle.net/SJGLF/1/
var myData = JSON.parse(jsonData);
for(var i in myData)
{
console.log(i + " = " + myData[i]);
}
Are you looking for this?
success: function (data)
{
var myObj = JSON.parse(data.d);
},

how to pass an array of strings from jQuery to controller

How can I pass an array of strings to a controller in asp.net mvc4?
Here is my code
jQuery:
function FnSaveAnalyses(){
var checked = [];
for (var i in checkedIds) {
if (checkedIds[i]) {
checked.push(i);
}
}
alert(checked); // it shows all the records without problem
var url = urlBiologieDemande + "Save";
$.post(
url,
data = { values: checked},
traditional= true,
success = function (data) {
DataSaved();
});
}
Controller
public ActionResult save(string[] values)
{
//Traitement
}
When debugging, I get null values.
POST IT AS JSON array.
var checked = [];
for (var i in checkedIds) {
if (checkedIds[i]) {
checked.push(i);
}
}
var url = urlBiologieDemande + "Save";
$.ajax({
type: 'Post',
dataType: 'json',
url: url ,
data: JSON.stringify(values:checked),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
}
});
then get the JSON in the Controller
and Parse it ..
see this

Pass Dictionary<String,List<String>> to Javascript array

This is my web service
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Dictionary<string,List<string>> GetCategorias()
{
var diccionario = new Dictionary<string, List<string>>();
var categoria = "Recursos Humanos";
diccionario.Add(categoria,new List<string>());
diccionario[categoria].Add("Busqueda de recursos");
diccionario[categoria].Add("Busqueda de recursos humanos");
var categoria1 = "Informatica";
diccionario.Add(categoria1, new List<string>());
diccionario[categoria1].Add("IT");
diccionario[categoria1].Add("Departamento de Insfractructura");
//var serializer = new JavaScriptSerializer();
//string json = serializer.Serialize((object)diccionario);
return diccionario;
}
I received the dictionary in Javascript as:
function get_Categorias_Comunidades() {
$.ajax({
type: "POST",
url: "Lista_Categoria_comunidad.asmx/GetCategorias",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: llamada_Webservice,
error: llamada_Error
});
}
function llamada_Webservice(peticion) {
debugger;
}
How do I parse the keys and values to an array?
Something like this
function llamada_Webservice(peticion) {
var categories = peticion;
for(item in categories{ // Data is saved in the variable named d if it's ASP.NET WebService
var categoria = item; // The name
var list = categories[item]; // The array that you could loop thru
}
}

MVC JsonResult Method not accepting parameter

I have an MVC JsonResult Method that accepts one string parameter:
public JsonResult GetDestinations(string countryId)
{
List<Destination> destinations = new List<Destination>();
string destinationsXml = SharedMethods.GetDestinations();
XDocument xmlDoc = XDocument.Parse(destinationsXml);
var d = from country in xmlDoc.Descendants("Country")
from destinationsx in country.Elements("Destinations")
from destination in destinationsx.Elements("Destination")
where (string)country.Attribute("ID") == countryId
select new Destination
{
Name = destination.Attribute("Name").Value,
ID = destination.Attribute("ID").Value,
};
destinations = d.ToList();
return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
With a jquery method calling the method:
//Fetch Destinations
$("#Country").change(function () {
var countryId = $("#Country > option:selected").attr("value");
$("#Destination").html("");
$("#Resort").html("");
$("#Resort").append($("<option></option>").val(0).html("---Select---"));
$.ajax({
type: "POST",
traditional: true,
url: "/Destinations/GetDestinations",
data: "{countryId:'" + countryId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
BindDestinationSelect(msg)
}
});
});
However, the JsonResult seems to only receive a null parameter. Even though Firebug is showing that a parameter is being passed:
JSON
countryId
"11"
Source
{countryId:'11'}
Any ideas? Thanks
I think the problem is in how you are actually passing the data, you are doing so as a string:
data: "{countryId:'" + countryId + "'}",
When in reality, you should be using a structure on the client side;
data: { countryId: countryId },
jQuery should be able to handle passing the id correctly then. As you are doing it now, it is trying to send JSON to the server, which is not what MVC is expecting, it's expecting a POST with name/value pairs.
You might also want to consider the jQuery Form Plugin, as it makes serializing your Javascript structures into POST data very easy.
Ah, after much searching I've discovered the reason why it fails.
Nothing to do with malformed JSON etc, but rather the fact that the controller method doesnt know what to expect if you try to pass it JSON values:
http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=863
So in my case, I've just elected to pass it a single string value.
$("#Country").change(function () {
var countryId = $("#Country > option:selected").attr("value");
$("#Destination").html("");
$("#Resort").html("");
$("#Resort").append($("<option></option>").val(0).html("---Select---"));
$.ajax({
type: "POST",
traditional: true,
url: "/Destinations/GetDestinations",
data: "countryId=" + countryId,
success: function (msg) {
BindDestinationSelect(msg.Data)
}
});
Here I suggest you to decorate your action with HttpPost attribute
Like :-
[HttpPost]
public JsonResult GetDestinations(string countryId)
{
List<Destination> destinations = new List<Destination>();
string destinationsXml = SharedMethods.GetDestinations();
XDocument xmlDoc = XDocument.Parse(destinationsXml);
var d = from country in xmlDoc.Descendants("Country")
from destinationsx in country.Elements("Destinations")
from destination in destinationsx.Elements("Destination")
where (string)country.Attribute("ID") == countryId
select new Destination
{
Name = destination.Attribute("Name").Value,
ID = destination.Attribute("ID").Value,
};
destinations = d.ToList();
return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
public JsonResult BindAllData(string Userid)
{
List<VoteList> list = new List<VoteList>();
var indexlist = db.TB_WebSites.ToList();
int i = 0;
var countlist = db.Tb_Votes.ToList();
var VCountList = db.Tb_Votes.ToList();
foreach (TB_WebSites vt in indexlist)
{
bool voted = false;
}
return Json(new { List = _list });
}
function DataBind() {
$("#LoadingDatas").show();
var userid = $("#FBUserId").text();
//alert('Data : ' + userid);
var InnerHtml = "";
$.ajax(
{
url: '/Gitex/BindAllData/',
type: 'POST',
data: { "Userid": userid },
dataType: 'json',
async: true,
success: function (data) {
//alert('Done');
//alert(data.List.length);
for (var i = 0; i < data.List.length; i++) {
});
}
Try this, it worked for me
jQuery function
success :function(Destinations)

Categories