Api Controller: Json decapitalizes the names of properties - json

I have an api controller in my webcore application:
[Route("api/[controller]")]
public class DataController : Controller
{
protected ApplicationDbContext dbContext;
public DataController(ApplicationDbContext dc)
{
dbContext = dc;
}
[HttpGet("Categories")]
public List<Category> GetCategories()
{
var l = dbContext.Categories.OrderBy(c => c.Name).ToList();
return l;
}
}
And the class:
public class Category
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
When I Invoke the controller action to get the categories, in the response the name of properties are all decapitalized. That is:
Id becomes id,
Name becomes name,
Description becomes description.
**Edit:
I have tried also:
[HttpGet("Test")]
public IActionResult Test()
{
var l = dbContext.Categories.OrderBy(c => c.Name).ToList();
return Json(l);
}
And still the properties are all decapitalized

/// <summary>
/// Welcome Note Message
/// </summary>
/// <returns>In a Json Format</returns>
public JsonResult WelcomeNote()
{
Category cs = new Category();
cs.Id = 123456;
cs.Name = "ExampleName";
cs.Description = "Abcd";
return Json(cs, JsonRequestBehavior.AllowGet);
}
This, I am getting from above code which you want I guess
Refer this for more good Examples

Related

Service Stack POST-Request Body-Format / Transformation

iam using a RequestClass with the Route anotation to call a Json-Client POST method.
Now, while the paramters are structured like this
public class GetTicketRequest: IReturn<JsonObject>
{
public string CartId {
get;
set;
}
public string PriceId {
get;
set;
}
}
The BackendAPI needs them to be nesten in "data" in the json request, so more like
{
"data":[
{"cartid":123,
"priceId":11}]
}
Is there any way to transfrom the request object for the body before calling
JsonServiceClient _restClient = new JsonServiceClient(baseUrl);
JsonObject oneResponse = _restClient.Post(options);
This solution is useful where many DTOs require to be wrapped & converted, and is highly reusable, with no changes to your existing DTOs.
You can convert the requests of the JsonServiceClient by overriding the methods that handle preparing the requests for sending. Which means implementing your own extended JsonServiceClient as given below.
If you want to do this for all verbs then you override it's Send<TResponse> methods (otherwise, if it's just for POST then uncomment the commented out code, and remove the Send methods).
public class MyJsonServiceClient : JsonServiceClient
{
public Dictionary<Type, Func<object, object>> DtoConverters = new Dictionary<Type, Func<object, object>>();
public MyJsonServiceClient() {}
public MyJsonServiceClient(string baseUri) : base(baseUri) {}
public MyJsonServiceClient(string syncReplyBaseUri, string asyncOneWayBaseUri) : base(syncReplyBaseUri, asyncOneWayBaseUri) {}
public override TResponse Send<TResponse>(object request)
{
return base.Send<TResponse>(ConvertRequest(request));
}
public override TResponse Send<TResponse>(string httpMethod, string relativeOrAbsoluteUrl, object request)
{
return base.Send<TResponse>(httpMethod, relativeOrAbsoluteUrl, ConvertRequest(request));
}
/*
public override TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object requestDto)
{
return base.Post(relativeOrAbsoluteUrl, ConvertRequest(requestDto));
}
*/
object ConvertRequest(object request)
{
Type dtoType = request.GetType();
return (DtoConverters.ContainsKey(dtoType)) ? DtoConverters[dtoType](request) : request;
}
}
Usage:
So given this DTO:
[Route("/test", "POST")]
public class TicketRequest : IReturnVoid
{
public string CartId { get; set; }
public string PriceId { get; set; }
}
You simply add the converter:
var client = new MyJsonServiceClient("http://localhost:9000");
// Simple converter for TicketRequest
client.DtoConverters.Add(typeof(TicketRequest), dto => {
var d = (TicketRequest)dto;
return new {
data = new {
CartId = d.CartId.ToInt(),
PriceId = d.PriceId.ToInt()
}
};
});
client.Post(new TicketRequest { CartId = "123", PriceId = "456" });
i solved this issue using a typed data property
public class GetTicketRequest: IReturn<JsonObject>
{
public class TicketCreateData
{
public int priceId {
get;
set;
}
}
public string CartId {
get;
set;
}
public string PriceId {
get;
set;
}
public List<TicketCreateData> data {
get {
var list = new List<TicketCreateData>();
list.Add(new TicketCreateData {
priceId = this.PriceId.ToInt()
});
return list;
}
set {
data = value;
}
}
}
To notes on this:
if neede, use DataContract/DataMember(Name="") to rename fields or only do partial serializing
Do never use structs for, like in this case, the data class - they are not serializeable at all
in my spefici case data even needs to be an array, thats why i used the list

.NET NewtonSoft JSON deserialize map to a different property name

I have following JSON string which is received from an external party.
{
"team":[
{
"v1":"",
"attributes":{
"eighty_min_score":"",
"home_or_away":"home",
"score":"22",
"team_id":"500"
}
},
{
"v1":"",
"attributes":{
"eighty_min_score":"",
"home_or_away":"away",
"score":"30",
"team_id":"600"
}
}
]
}
My mapping classes:
public class Attributes
{
public string eighty_min_score { get; set; }
public string home_or_away { get; set; }
public string score { get; set; }
public string team_id { get; set; }
}
public class Team
{
public string v1 { get; set; }
public Attributes attributes { get; set; }
}
public class RootObject
{
public List<Team> team { get; set; }
}
The question is that I don't like the Attributes class name and the attributes field names in the Team class. Instead, I want it to be named TeamScore and also to remove _ from the field names and give proper names.
JsonConvert.DeserializeObject<RootObject>(jsonText);
I can rename Attributes to TeamScore, but if I change the field name (attributes in the Team class), it won't deserialize properly and gives me null. How can I overcome this?
Json.NET - Newtonsoft has a JsonPropertyAttribute which allows you to specify the name of a JSON property, so your code should be:
public class TeamScore
{
[JsonProperty("eighty_min_score")]
public string EightyMinScore { get; set; }
[JsonProperty("home_or_away")]
public string HomeOrAway { get; set; }
[JsonProperty("score ")]
public string Score { get; set; }
[JsonProperty("team_id")]
public string TeamId { get; set; }
}
public class Team
{
public string v1 { get; set; }
[JsonProperty("attributes")]
public TeamScore TeamScores { get; set; }
}
public class RootObject
{
public List<Team> Team { get; set; }
}
Documentation: Serialization Attributes
If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me
Usage:
var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new CustomContractResolver();
this.DataContext = JsonConvert.DeserializeObject<CountResponse>(jsonString, settings);
Logic:
public class CustomContractResolver : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; set; }
public CustomContractResolver()
{
this.PropertyMappings = new Dictionary<string, string>
{
{"Meta", "meta"},
{"LastUpdated", "last_updated"},
{"Disclaimer", "disclaimer"},
{"License", "license"},
{"CountResults", "results"},
{"Term", "term"},
{"Count", "count"},
};
}
protected override string ResolvePropertyName(string propertyName)
{
string resolvedName = null;
var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".
/// <summary>
/// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not
/// let the JsonProperty control everything.
/// </summary>
/// <typeparam name="T"></typeparam>
public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; set; }
public IgnoreJsonPropertyResolver()
{
this.PropertyMappings = new Dictionary<string, string>();
var properties = ReflectionHelper<T>.GetGetProperties(false)();
foreach (var propertyInfo in properties)
{
var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
if (jsonProperty != null)
{
PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
}
}
}
protected override string ResolvePropertyName(string propertyName)
{
string resolvedName = null;
var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
Usage:
var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
var model = new PlanViewModel() {Amount = 100};
var strModel = JsonConvert.SerializeObject(model,settings);
Model:
public class PlanViewModel
{
/// <summary>
/// The customer is charged an amount over an interval for the subscription.
/// </summary>
[JsonProperty(PropertyName = "RecurringPrice")]
public double Amount { get; set; }
/// <summary>
/// Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
/// months or years depending on the value for interval_unit.
/// </summary>
public int Interval { get; set; } = 1;
/// <summary>
/// Number of free trial days that can be granted when a customer is subscribed to this plan.
/// </summary>
public int TrialPeriod { get; set; } = 30;
/// <summary>
/// This indicates a one-time fee charged upfront while creating a subscription for this plan.
/// </summary>
[JsonProperty(PropertyName = "SetupFee")]
public double SetupAmount { get; set; } = 0;
/// <summary>
/// String representing the type id, usually a lookup value, for the record.
/// </summary>
[JsonProperty(PropertyName = "TypeId")]
public string Type { get; set; }
/// <summary>
/// Billing Frequency
/// </summary>
[JsonProperty(PropertyName = "BillingFrequency")]
public string Period { get; set; }
/// <summary>
/// String representing the type id, usually a lookup value, for the record.
/// </summary>
[JsonProperty(PropertyName = "PlanUseType")]
public string Purpose { get; set; }
}
Expanding Rentering.com's answer, in scenarios where a whole graph of many types is to be taken care of, and you're looking for a strongly typed solution, this class can help, see usage (fluent) below. It operates as either a black-list or white-list per type. A type cannot be both (Gist - also contains global ignore list).
public class PropertyFilterResolver : DefaultContractResolver
{
const string _Err = "A type can be either in the include list or the ignore list.";
Dictionary<Type, IEnumerable<string>> _IgnorePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
Dictionary<Type, IEnumerable<string>> _IncludePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
public PropertyFilterResolver SetIgnoredProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
{
if (propertyAccessors == null) return this;
if (_IncludePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);
var properties = propertyAccessors.Select(GetPropertyName);
_IgnorePropertiesMap[typeof(T)] = properties.ToArray();
return this;
}
public PropertyFilterResolver SetIncludedProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
{
if (propertyAccessors == null)
return this;
if (_IgnorePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);
var properties = propertyAccessors.Select(GetPropertyName);
_IncludePropertiesMap[typeof(T)] = properties.ToArray();
return this;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
var isIgnoreList = _IgnorePropertiesMap.TryGetValue(type, out IEnumerable<string> map);
if (!isIgnoreList && !_IncludePropertiesMap.TryGetValue(type, out map))
return properties;
Func<JsonProperty, bool> predicate = jp => map.Contains(jp.PropertyName) == !isIgnoreList;
return properties.Where(predicate).ToArray();
}
string GetPropertyName<TSource, TProperty>(
Expression<Func<TSource, TProperty>> propertyLambda)
{
if (!(propertyLambda.Body is MemberExpression member))
throw new ArgumentException($"Expression '{propertyLambda}' refers to a method, not a property.");
if (!(member.Member is PropertyInfo propInfo))
throw new ArgumentException($"Expression '{propertyLambda}' refers to a field, not a property.");
var type = typeof(TSource);
if (!type.GetTypeInfo().IsAssignableFrom(propInfo.DeclaringType.GetTypeInfo()))
throw new ArgumentException($"Expresion '{propertyLambda}' refers to a property that is not from type '{type}'.");
return propInfo.Name;
}
}
Usage:
var resolver = new PropertyFilterResolver()
.SetIncludedProperties<User>(
u => u.Id,
u => u.UnitId)
.SetIgnoredProperties<Person>(
r => r.Responders)
.SetIncludedProperties<Blog>(
b => b.Id)
.Ignore(nameof(IChangeTracking.IsChanged)); //see gist
I am using JsonProperty attributes when serializing but ignoring them when deserializing using this ContractResolver:
public class IgnoreJsonPropertyContractResolver: DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
foreach (var p in properties) { p.PropertyName = p.UnderlyingName; }
return properties;
}
}
The ContractResolver just sets every property back to the class property name (simplified from Shimmy's solution). Usage:
var airplane= JsonConvert.DeserializeObject<Airplane>(json,
new JsonSerializerSettings { ContractResolver = new IgnoreJsonPropertyContractResolver() });
Also if you want to ignore something use this
[JsonIgnore]
public int Id { get; set; }
[JsonProperty("id")]
Public string real_id { get; set; }

How to convert json dynamic object to c# entity

When I make mvc ajax json post applicaiton, there is a trouble to convert json dynamic object to entity.
In my app, movie is a business entity, json object has row status property than movie entity. When json data is posted to mvc server side, it can be converted to dynamic object, everyting is ok in this stage. But after handling some logic to each row status, it is needed to convert dynamic object to movie business entity, then begin database transaction logic. But there is a troulbe even I try different method to cast the object.
please did someone use the same cast method? thanks your advice or reply.
public class movie
{
public int id
{
get;
set;
}
public string title
{
get;
set;
}
}
/// <summary>
/// Convert Json Object to Entity
/// </summary>
/// <param name="id">ajax post value
/// format: {"id": "{\"id\": 1, \"title\": \"sharlock\", \"RowStatus\": \"deleted\"}"}
/// </param>
[AllowAnonymous]
[HttpPost]
public void DoJsonSimple(string id)
{
string title;
var entity = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(id);
//*** entity is dynamic object
//*** entity.id, entity.title and entity.RowStauts can be accessed.
int first = entity.id;
var status = entity.RowStatus;
if (status == "deleted")
{
//*** m1 is null
//*** m1.title can not be accessed
movie m1 = entity as movie;
title = m1.title;
//*** m2 is an empty object
//*** m2.id is 0, m2.title is null
var m2 = AutoMapperHelper<dynamic, movie>.AutoConvertDynamic(entity);
title = m2.title;
//*** Exception: Object must implement IConvertible.
var m3 = EmitMapper.EMConvert.ChangeTypeGeneric<dynamic, movie>(entity);
title = m3.title;
}
}
Just create another class for the rows.
public class Request
{
[JsonProperty("id")]
public string Json { get; set; }
}
public class Movie
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
}
// either this for variant 1...
public class Row
{
public string RowStatus { get; set; }
}
// or that for variant 2...
public class MovieRow : Movie
{
public string RowStatus { get; set; }
}
[AllowAnonymous]
[HttpPost]
public void DoJsonSimple_Variant1(string id)
{
var json = JsonConvert.DeserializeObject<Request>(id).Json;
var entity = JsonConvert.DeserializeObject<MovieRow>(json);
var row = JsonConvert.DeserializeObject<Row>(json);
switch (row.RowStatus)
{
case "deleted":
// delete entity
break;
// ...
}
// ...
}
[AllowAnonymous]
[HttpPost]
public void DoJsonSimple_Variant2(string id)
{
var json = JsonConvert.DeserializeObject<Request>(id).Json;
var row = JsonConvert.DeserializeObject<MovieRow>(json);
var entity = (Movie)row;
switch (row.RowStatus)
{
case "deleted":
// delete entity
break;
// ...
}
// ...
}

MVC3 JSON Serialization: How to control the property names?

I want to serialize a simple object to JSON:
public class JsonTreeNode
{
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "isFolder")]
public bool IsFolder { get; set; }
[DataMember(Name = "key")]
public string Key { get; set; }
[DataMember(Name = "children")]
public IEnumerable<JsonTreeNode> Children { get; set; }
[DataMember(Name = "select")]
public bool SelectedOnInit { get; set; }
}
But whenever I do it:
return Json(tree, JsonRequestBehavior.AllowGet);
The property names are not as specified in the [DataMember] section, but similar to the ones defined directly in the class e.g. in the case of SelectOnInit it is not select but SelectOnInit.
What am I doing wrong?
I solved the problem by using the technique provided in the answer in this question:
ASP.NET MVC: Controlling serialization of property names with JsonResult
Here is the class I made:
/// <summary>
/// Similiar to <see cref="JsonResult"/>, with
/// the exception that the <see cref="DataContract"/> attributes are
/// respected.
/// </summary>
/// <remarks>
/// Based on the excellent stackoverflow answer:
/// https://stackoverflow.com/a/263416/1039947
/// </remarks>
public class JsonDataContractActionResult : ActionResult
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="data">Data to parse.</param>
public JsonDataContractActionResult(Object data)
{
Data = data;
}
/// <summary>
/// Gets or sets the data.
/// </summary>
public Object Data { get; private set; }
/// <summary>
/// Enables processing of the result of an action method by a
/// custom type that inherits from the ActionResult class.
/// </summary>
/// <param name="context">The controller context.</param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var serializer = new DataContractJsonSerializer(Data.GetType());
string output;
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, Data);
output = Encoding.UTF8.GetString(ms.ToArray());
}
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.Write(output);
}
}
Usage:
public ActionResult TestFunction()
{
var testObject = new TestClass();
return new JsonDataContractActionResult(testObject);
}
I also had to modify the initial class:
// -- The DataContract property was added --
[DataContract]
public class JsonTreeNode
{
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "isFolder")]
public bool IsFolder { get; set; }
[DataMember(Name = "key")]
public string Key { get; set; }
[DataMember(Name = "children")]
public IEnumerable<JsonTreeNode> Children { get; set; }
[DataMember(Name = "select")]
public bool SelectedOnInit { get; set; }
}
This is a solution that uses newtonsoft Json.net (for performance concerned)
I've found part of the solution here and on SO
public class JsonNetResult : ActionResult
{
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult(object data, Formatting formatting)
: this(data)
{
Formatting = formatting;
}
public JsonNetResult(object data):this()
{
Data = data;
}
public JsonNetResult()
{
Formatting = Formatting.None;
SerializerSettings = new JsonSerializerSettings();
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data == null) return;
var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
var serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
So that in my controller, I can do that
return new JsonNetResult(result);
In my model, I can now have:
[JsonProperty(PropertyName = "n")]
public string Name { get; set; }
Note that now, you have to set the JsonPropertyAttribute to every property you want to serialize.

Entity Framework 4.1: Data from repository not displaying via JSON

I am using Entity Framework 4.1 code first and ASP.NET MVC 3. I have a Yahoo User Interface (YUI) datatable on my view. I am getting the data (to populate the grid via JSON).
Flow of getting data:
Controller -> Service -> Repository
My context setup:
public DbSet<Category> Categories { get; set; }
Original Repositry:
public IEnumerable<Category> GetAll()
{
return db.Categories.ToList();
}
Call to this repository method from my service layer:
public IEnumerable<Category> GetAll()
{
return categoryRepository.GetAll();
}
My action method to retrieve the data and to pass it to the YUI datatable:
public ActionResult JsonCategoriesList()
{
JsonEncapsulatorDto<Category> data = new JsonEncapsulatorDto<Category>
{
DataResultSet = categoryService.GetAll()
};
return Json(data, JsonRequestBehavior.AllowGet);
}
JsonEncapsulatorDto code:
public class JsonEncapsulatorDto<T>
{
public IEnumerable<T> DataResultSet { get; set; }
}
When I use it this way then there is an error in the datatable. I don't know how to view the error. Nothing is displayed. I debugged and I saw that there is a count of 7 in the DataResultSet. So what I did was to change the repository to use some test data and then it worked. What is the difference and how do I get it to display my results?
Repository with test data:
public IEnumerable<Category> GetAll()
{
List<Category> list = new List<Category>();
list.Add(new Category { Name = "Brendan" });
list.Add(new Category { Name = "Charlene" });
return list;
//return db.Categories.ToList();
}
Not sure if you guys want to see my setup of the categories datatable:
<div id="dtCategories"></div>
<script type="text/javascript">
YAHOO.util.Event.onDOMReady(function () {
var yuiDataSource = YAHOO.util.DataSource;
var yuiPaginator = YAHOO.widget.Paginator;
var yuiDataTable = YAHOO.widget.DataTable;
var dtCategoriesColumnDefs, dtCategoriesDataSource;
var dtCategoriesConfigs, dtCategoriesDataTable;
dtCategoriesColumnDefs = [
{ key: 'Name', label: 'Name' }
];
dtCategoriesDataSource = new YAHOO.util.DataSource('#Url.RouteUrl (Url.AdministrationCategoryJsonCategoriesList())');
dtCategoriesDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
dtCategoriesDataSource.responseSchema = {
resultsList: 'DataResultSet',
fields: [
{ key: 'Name' }
]
};
dtCategoriesDataTable = new YAHOO.widget.DataTable('dtCategories', dtCategoriesColumnDefs, dtCategoriesDataSource);
});
</script>
UPDATE:
Category class:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public bool IsActive { get; set; }
public int? ParentCategoryId { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
}
Context class:
public class PbeContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Tutorial> Tutorials { get; set; }
protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
{
dbModelBuilder.Entity<Category>()
.HasOptional(c => c.ParentCategory)
.WithMany(c => c.ChildCategories)
.HasForeignKey(p => p.ParentCategoryId);
}
}
UPDATE 2:
I have another view that that gets a list of Product objects (no circular references) and it populates fine. I debugged to see what the data looks like when it is returned. And this is how the objects looked like in the list:
Categories:
[0] [System.Data.Entity.DynamicProxies.Category_9E42BCEDDE8AA695F718BEBE2224E1D34291FCAF82F801F4995EEB8449479C93]
[1] [System.Data.Entity.DynamicProxies.Category_9E42BCEDDE8AA695F718BEBE2224E1D34291FCAF82F801F4995EEB8449479C93]
[2] [System.Data.Entity.DynamicProxies.Category_9E42BCEDDE8AA695F718BEBE2224E1D34291FCAF82F801F4995EEB8449479C93]
...and so on...
Products:
[0] = {MyProject.Core.DomainObjects.Product}
[1] = {MyProject.Core.DomainObjects.Product}
[2] = {MyProject.Core.DomainObjects.Product}
Can it maybe because of how the data is returned??
No idea where your error is. Maybe a recursive Category model (usually that's what happens when you don't use view models and try to pass your EF domain models to the view)? In your example you only need to show a table containing one column which is the name of the category. Passing an entire domain IEnumerable<Category> is like a crime. Maybe missing scripts? Maybe this AdministrationCategoryJsonCategoriesList extension method?
Here's a full working example that I wrote for you and that might get you started:
Model:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public bool IsActive { get; set; }
public int? ParentCategoryId { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
// Obviously this will be in your repository but for the purpose of
// this demonstration let's hardcode some data
public static IEnumerable<Category> GetAll()
{
List<Category> list = new List<Category>();
list.Add(new Category { Name = "Brendan" });
list.Add(new Category { Name = "Charlene" });
return list;
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult JsonCategoriesList()
{
var data = Category.GetAll().Select(x => new
{
// We select only what we need for our view => the name
// if you need something else, well, select it here
Name = x.Name
}).ToList();
return Json(new { DataResultSet = data }, JsonRequestBehavior.AllowGet);
}
}
View:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>YUI Test</title>
<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.9.0/build/datatable/assets/skins/sam/datatable.css">
</head>
<body>
<div id="dtCategories"></div>
<script src="http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/element/element-min.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/datasource/datasource-min.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/datatable/datatable-min.js"></script>
<script type="text/javascript">
YAHOO.util.Event.onDOMReady(function () {
var yuiDataSource = YAHOO.util.DataSource;
var yuiDataTable = YAHOO.widget.DataTable;
var dtCategoriesColumnDefs, dtCategoriesDataSource;
var dtCategoriesConfigs, dtCategoriesDataTable;
dtCategoriesColumnDefs = [{ key: 'Name', label: 'Name'}];
dtCategoriesDataSource = new YAHOO.util.DataSource('#Url.Action("JsonCategoriesList")');
dtCategoriesDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
dtCategoriesDataSource.responseSchema = {
resultsList: 'DataResultSet',
fields: [{ key: 'Name'}]
};
dtCategoriesDataTable = new YAHOO.widget.DataTable(
'dtCategories',
dtCategoriesColumnDefs,
dtCategoriesDataSource
);
});
</script>
</body>
</html>
Please post the Category type definition to see if there is a circular reference, This might help: Json and Circular Reference Exception