First please start from picture i have attached the json output view. On picture you will see i was able to assign value only to the root level objects but on child level i failed to assign value properly which i need. My main goal is get output exactly like Json code bellow. How can i fix my controller to get exactly example json type output from JavaScriptSerializer?
Controller:
var root = new RootObject();
root.name = "Jan Kowalski";
root.email = "jan.kowalski#wp.pl";
root.dayOfCycle = "10";
//root.tags.Add(new Tag
//{
// tagId = "Xw",
//});
//root.scoring = 25;
//root.customFieldValues.Add(new CustomFieldValue
//{
// customFieldId = "n",
// //value = "white", value should be list
//});
root.ipAddress = "89.206.36.193";
var camp = new Campaign();
camp.campaignId = "jf7e3jn";
var jsBody = new JavaScriptSerializer().Serialize(root);
Model class:
public class Campaign
{
public string campaignId { get; set; }
}
public class Tag
{
public string tagId { get; set; }
}
public class CustomFieldValue
{
public string customFieldId { get; set; }
public List<string> value { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string email { get; set; }
public string dayOfCycle { get; set; }
public Campaign campaign { get; set; }
public List<Tag> tags { get; set; }
public int scoring { get; set; }
public List<CustomFieldValue> customFieldValues { get; set; }
public string ipAddress { get; set; }
}
Json body i want from JavaScriptSerializer:
{
"name": "Jan Kowalski",
"email": "jan.kowalski#wp.pl",
"dayOfCycle": "10",
"campaign": {
"campaignId": "jf7e3jn"
},
"tags": [
{
"tagId": "Xw"
},
{
"tagId": "Nn"
}
],
"scoring": 25,
"customFieldValues": [
{
"customFieldId": "n",
"value": [
"white"
]
}
],
"ipAddress": "89.206.36.193"
}
As commented already, for the sake of completeness:
Missing: root.campaign = camp; just before creation of jsBody
Missing root.tags = new List<Tag>(); to prevent Null Reference Exception, just before root.tags.Add is executed
Related
Below is Json payload i am fetching from a API:
[
{
"id": "8c0e33ea-51af-44e0-8cb5-ef93703a4e6c",
"storeId": "xyz",
"name": "009DI",
"styleColors": []
},
{
"id": "f6284195-0f58-4f6b-a3b8-d5d22d1f7e63",
"storeId": "abc",
"name": "A001A",
"styleColors": []
}
]
Classes created for deserialization:
public class BINobjects
{
[JsonProperty(PropertyName = "binid")]
public string binid { get; set; }
[JsonProperty(PropertyName = "storeId")]
public string storeId { get; set; }
[JsonProperty(PropertyName = "binname")]
public string binname { get; set; }
}
public class BINdetails
{
[JsonProperty(PropertyName = "BINobjects")]
//public pages pages { get; set; }
public IList<BINobjects> BINobjects { get; set; }
}
Below is how I am trying to de-serialize it as a List of BINdetails objects
BINobjects BINdetails = JsonConvert.DeserializeObject<List<BINobjects>>(result);
Error:
cannot implicitly convert 'system.collections.generic.list to "tools.binobjects'. However, below code works but reading only 1 column from source.
var str = JsonConvert.DeserializeObject<List<BINobjects>>(result);
Is there a way to read directly into the object than into a variable. I am fine with whatever that works.
I got it fixed by editing the class property names:
public class BINobjects
{
[JsonProperty(PropertyName = "id")]
public string binid { get; set; }
[JsonProperty(PropertyName = "storeId")]
public string storeId { get; set; }
[JsonProperty(PropertyName = "name")]
public string binname { get; set; }
}
And then reading into variable:
var str = JsonConvert.DeserializeObject<List<BINobjects>>(result);
I am new in ASP.Net and MVC5 programming,in fact I have a problem,I have this Class "Student":
namespace Project.Entities.Models
{
public partial class Student : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
[ForeignKey("ClassId")]
public virtual Class Class { get; set; }
public Int64 ClassId { get; set; }
[ForeignKey("ImageId")]
public virtual Image Image { get; set; }
public Int64 ImageId { get; set; }
public virtual List<Mark> Marks { get; set; }
public virtual List<Punishment> Punishments { get; set; }
public Student()
{
Marks = new List<Mark>();
Punishments = new List<Punishment>();
}
}
Class "Mark":
namespace SMA.Entities.Models
{
public partial class Mark : BaseEntity
{
public int Score { get; set; }
public string Note { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; }
public Int64 StudentId { get; set; }
}
}
I want to get the Marks of each Student,but I don't know How,
this is what I get in JSON result:
[
{
FirstName: "Student ",
LastName: "1",
Class: null,
ClassId: 1,
Image: null,
ImageId: 1,
Marks: [ ],
Punishments: [ ],
Id: 1,
ObjectState: 0
},
{
FirstName: "Student ",
LastName: "2",
Class: null,
ClassId: 2,
Image: null,
ImageId: 2,
Marks: [ ],
Punishments: [ ],
Id: 2,
ObjectState: 0
}
]
so please,have you any idea about,how can I access the Marks data for each Student
thanks for help
Assuming that you have an Id field in your Student entity that is the primary key (you didn't show it in the question, but I assume it was omitted), try changing this:
public virtual List<Mark> Marks { get; set; }
public virtual List<Punishment> Punishments { get; set; }
to
public virtual ICollection<Mark> Marks { get; set; }
public virtual ICollection<Punishment> Punishments { get; set; }
I created two selector using Exp-Func I want to execute both in a single query. Code is as follows:
Expression<Func<Scholar, ScholarCultureWatchListView>> selector = z => new ScholarCultureWatchListView
{
ScholarId = z.ID,
Name = z.FirstName + " " + z.LastName
};
Expression<Func<Scholar, ScholarCultureWatchListView>> selector2 = z => new ScholarCultureWatchListView
{
Grade = z.CurrentGrade
};
var result= from s in db.Scholars
select new ScholarCultureWatchListView
{
**?????What is write here (selector, selector2)**
}
public class ScholarCultureWatchListView
{
public long ScholarId { get; set; }
public string Name { get; set; }
public Grade? Grade { get; set; }
public bool? HoldOverSkip { get; set; }
public Grade? GradeHoldOver { get; set; }
public bool? Iep { get; set; }
public int Tardies { get; set; }
public int Absences { get; set; }
public int YtdSuspensions { get; set; }
....
}
please solve my problem.
Thanks
If you want to get two separate instances of ScholarCultureWatchListView returned from a single call, you can do for example this (and you don't need selectors at all):
var result = from s in db.Scholars
select new[]
{
new ScholarCultureWatchListView
{
ScholarId = s.ID,
Name = s.FirstName + " " + z.LastName
},
new ScholarCultureWatchListView
{
Grade = z.CurrentGrade
},
};
I have a simple object model
public class License
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string CreationUserId { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string LastModifiedUserId { get; set; }
public string LicenseName { get; set; }
public LicenseType LicenseType { get; set; }
public State State { get; set; }
public DateTime DateIssued { get; set; }
public int ValidFor { get; set; }
}
public class State
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string CreationUserId { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string LastModifiedUserId { get; set; }
[StringLength(2)]
[Required]
public string Name { get; set; }
[Display(Name = "Long Name")]
[Required, StringLength(25)]
public string LongName { get; set; }
}
public class LicenseType
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string CreationUserId { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string LastModifiedUserId { get; set; }
[StringLength(100), Required]
public string Description { get; set; }
}
I am using the hot towel template breeze, durandal, knockout.
I have a simple add view model
var _licenseAdded = false;
var vm = {
states: ko.observableArray(context.states),
licenseTypes: ko.observableArray(context.licenseTypes),
viewAttached: function () {
var self = this;
$('input[name^="date"]').datepicker();
$('#validFor').spinner({
min: 365,
max: 3650,
step: 30
});
log('add Attached', null, true);
},
activate: function () {
var self = this;
self.original = context.manager.createEntity('License', { licenseName: 'Testing321', dateIssued: moment().format('L') }, null);
log('add Activated', null, true);
},
canDeactivate: function () {
if (_licenseAdded === false) {
return app.showMessage('Are you sure you want to leave this page?', 'Navigate', ['Yes', 'No']);
} else {
return true;
}
},
saveChanges: function () {
$.when(context.saveNewLicense()).done(function () {
_licenseAdded = true;
});
router.navigateTo('home');
},
original: undefined
};
return vm;
And here is my add.html, everything binds up fine and works beautifully until saving.
When I call saveChanges the saveBundle sent to the controller has no navigation properties attached that allow for the correct State and LicenseType to be stored I only get:
saveBundle {
"entities": [
{
"Id": -1,
"CreationUserId": null,
"LastModifiedUserId": null,
"LicenseName": "new for testing",
"DateIssued": "2013-03-11T04:00:00Z",
"ValidFor": 0,
"entityAspect": {
"entityTypeName": "License:#Volt.Telecom.Licensing.Models",
"entityState": "Added",
"originalValuesMap": {},
"autoGeneratedKey": {
"propertyName": "Id",
"autoGeneratedKeyType": "Identity"
}
}
}
],
"saveOptions": {
"allowConcurrentSaves": false
}
}
Don't think I can get much more vanilla than this. Why might this occur? When I am debugging on the client the state and licenseType navigationProperties are all correct and with the correct values.
I think the issue is that your EF model uses 'Independent Associations' instead of 'Foreign Key Assocations' (foreign key associations are the EF default). We do need to do a better job of documenting this assumption.
The reason for this requirement, which can be bypassed but with a substantial loss of functionality, is that the existence of foreign keys on the client is what allows breeze to automatically fix up relationships between entities that might be queried separately.
See the following MSDN article for more background: foreign-keys-in-the-entity-framework
My models for my blog :
namespace AlexPeta_2.Models
{
public class Article
{
public int ArticleId { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public char Published { get; set; }
public DateTime CreatedDate { get; set; }
public char AllowComment { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
}
namespace AlexPeta_2.Models
{
public class Comment
{
public int CommentId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string HomePage { get; set; }
public string Comm { get; set; }
public DateTime CreatedDate { get; set; }
}
}
namespace AlexPeta_2.Models
{
public class Tag
{
public int TagId { get; set; }
public string TagName { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
}
here are my dbsets:
public class BlogContext : DbContext
{
public DbSet<Article> Articles { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<Comment> Comments { get; set; }
}
here is my initializer :
public class BlogInitializer : DropCreateDatabaseIfModelChanges<BlogContext>
{
protected override void Seed(BlogContext context)
{
List<Tag> tags = new List<Tag>
{
new Tag { TagId = 1, TagName = "Javascript" },
new Tag { TagId = 2, TagName = "Bodybuilding" },
new Tag { TagId = 3, TagName = "Uncategorised" },
new Tag { TagId = 4, TagName = "CSS" },
new Tag { TagId = 5, TagName = "HTML/XHTML" },
new Tag { TagId = 6, TagName = "APEX" },
new Tag { TagId = 7, TagName = "PL/SQL" },
new Tag { TagId = 8, TagName = "Personal" },
new Tag { TagId = 9, TagName = "ASP" },
new Tag { TagId = 10, TagName = "MVC" },
new Tag { TagId = 11, TagName = "C#" },
new Tag { TagId = 12, TagName = "Snowboarding" }
};
tags.ForEach(t => context.Tags.Add(t));
context.SaveChanges();
}
}
The funny thing is : i ran the application with no Connection String in webconfig, it runs fine , i see all my tags in the controller but there is not Database file in APP_DATA ?? How come is that? or what happened?
If you do not provide a connection string, EF Code First creates the database with user credentials (windows) on the local SQLExpress instance. You can validate the same by using SQL Server Management Studio Express and logging on to the local instance.
Alex,
The connectionstring is actually derived automagically (i.e. by convention) from the dbcontext (in your case BlogContext), so you'll find that inside either sqlexpress or sqlcompact that you'll have a new db with the name that your dbcontext has.
good luck.