From my controller in mvc 4, I request a collection of objects from my model in database using entity framework:
[HttpPost]
public ActionResult RequestDbObjects()
{
List<MyObjectType> objCollection;
using (DataContext context = new DataContext())
{
objCollection= context.MyObjects.Where(o => o.TypeId == 1).OrderBy(k => k.Name).ToList();
}
return Json(objCollection);
}
Model:
[Table("MyObjects")]
public class MyObjectType
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
[ForeignKey("Type")]
public int TypeId { get; set; }
public virtual Type Type{ get; set; }
}
[Table("Type")]
public class Type
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
And in the view, using a script:
function recollectData() {
$.ajax({
url: "/Controller/RequestDbObjects/",
type: 'POST',
success: function (dataCollection) {
for(var obj in dataCollection)
{
var value = dataCollection[obj];
}
},
error: function () {
alert('Cannot retrieve the data');
}
});
};
In the above controller, first o all I call to the action in the controller which request data from database using entity framework, then from the list of objects returned to the script, I want to iterate on them, and for each of them read some attributes and do some stuff but I do not know how to do it.Ideas?