I am trying to do a simple JSON return but I am having issues I have the following below.
public JsonResult GetEventData()
{
var data = Event.Find(x => x.ID != 0);
return Json(data);
}
I get a HTTP 500 with the exception as shown in the title of this question. I also tried
var data = Event.All().ToList()
That gave the same problem.
Is this a bug or my implementation?
It seems that there are circular references in your object hierarchy which is not supported by the JSON serializer. Do you need all the columns? You could pick up only the properties you need in the view:
return Json(new
{
PropertyINeed1 = data.PropertyINeed1,
PropertyINeed2 = data.PropertyINeed2
});
This will make your JSON object lighter and easier to understand. If you have many properties, AutoMapper could be used to automatically map between DTO objects and View objects.
I had the same problem and solved by using Newtonsoft.Json;
var list = JsonConvert.SerializeObject(model,
Formatting.None,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return Content(list, "application/json");
This actually happens because the complex objects are what makes the resulting json object fails.
And it fails because when the object is mapped it maps the children, which maps their parents, making a circular reference to occur. Json would take infinite time to serialize it, so it prevents the problem with the exception.
Entity Framework mapping also produces the same behavior, and the solution is to discard all unwanted properties.
Just expliciting the final answer, the whole code would be:
public JsonResult getJson()
{
DataContext db = new DataContext ();
return this.Json(
new {
Result = (from obj in db.Things select new {Id = obj.Id, Name = obj.Name})
}
, JsonRequestBehavior.AllowGet
);
}
It could also be the following in case you don't want the objects inside a Result property:
public JsonResult getJson()
{
DataContext db = new DataContext ();
return this.Json(
(from obj in db.Things select new {Id = obj.Id, Name = obj.Name})
, JsonRequestBehavior.AllowGet
);
}
To sum things up, there are 4 solutions to this:
Solution 1: turn off ProxyCreation for the DBContext and restore it in the end.
private DBEntities db = new DBEntities();//dbcontext
public ActionResult Index()
{
bool proxyCreation = db.Configuration.ProxyCreationEnabled;
try
{
//set ProxyCreation to false
db.Configuration.ProxyCreationEnabled = false;
var data = db.Products.ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
finally
{
//restore ProxyCreation to its original state
db.Configuration.ProxyCreationEnabled = proxyCreation;
}
}
Solution 2: Using JsonConvert by Setting ReferenceLoopHandling to ignore on the serializer settings.
//using using Newtonsoft.Json;
private DBEntities db = new DBEntities();//dbcontext
public ActionResult Index()
{
try
{
var data = db.Products.ToList();
JsonSerializerSettings jss = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
var result = JsonConvert.SerializeObject(data, Formatting.Indented, jss);
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
}
Following two solutions are the same, but using a model is better because it's strong typed.
Solution 3: return a Model which includes the needed properties only.
private DBEntities db = new DBEntities();//dbcontext
public class ProductModel
{
public int Product_ID { get; set;}
public string Product_Name { get; set;}
public double Product_Price { get; set;}
}
public ActionResult Index()
{
try
{
var data = db.Products.Select(p => new ProductModel
{
Product_ID = p.Product_ID,
Product_Name = p.Product_Name,
Product_Price = p.Product_Price
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
}
Solution 4: return a new dynamic object which includes the needed properties only.
private DBEntities db = new DBEntities();//dbcontext
public ActionResult Index()
{
try
{
var data = db.Products.Select(p => new
{
Product_ID = p.Product_ID,
Product_Name = p.Product_Name,
Product_Price = p.Product_Price
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
}
JSON, like xml and various other formats, is a tree-based serialization format. It won't love you if you have circular references in your objects, as the "tree" would be:
root B => child A => parent B => child A => parent B => ...
There are often ways of disabling navigation along a certain path; for example, with XmlSerializer you might mark the parent property as XmlIgnore. I don't know if this is possible with the json serializer in question, nor whether DatabaseColumn has suitable markers (very unlikely, as it would need to reference every serialization API)
add [JsonIgnore] to virtuals properties in your model.
Using Newtonsoft.Json: In your Global.asax Application_Start method add this line:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
Its because of the new DbContext T4 template that is used for generating the EntityFramework entities. In order to be able to perform the change tracking, this templates uses the Proxy pattern, by wrapping your nice POCOs with them. This then causes the issues when serializing with the JavaScriptSerializer.
So then the 2 solutions are:
Either you just serialize and return the properties you need on the client
You may switch off the automatic generation of proxies by setting it on the context's configuration
context.Configuration.ProxyCreationEnabled = false;
Very well explained in the below article.
http://juristr.com/blog/2011/08/javascriptserializer-circular-reference/
Provided answers are good, but I think they can be improved by adding an "architectural" perspective.
Investigation
MVC's Controller.Json function is doing the job, but it is very poor at providing a relevant error in this case. By using Newtonsoft.Json.JsonConvert.SerializeObject, the error specifies exactly what is the property that is triggering the circular reference. This is particularly useful when serializing more complex object hierarchies.
Proper architecture
One should never try to serialize data models (e.g. EF models), as ORM's navigation properties is the road to perdition when it comes to serialization. Data flow should be the following:
Database -> data models -> service models -> JSON string
Service models can be obtained from data models using auto mappers (e.g. Automapper). While this does not guarantee lack of circular references, proper design should do it: service models should contain exactly what the service consumer requires (i.e. the properties).
In those rare cases, when the client requests a hierarchy involving the same object type on different levels, the service can create a linear structure with parent->child relationship (using just identifiers, not references).
Modern applications tend to avoid loading complex data structures at once and service models should be slim. E.g.:
access an event - only header data (identifier, name, date etc.) is loaded -> service model (JSON) containing only header data
managed attendees list - access a popup and lazy load the list -> service model (JSON) containing only the list of attendees
Avoid converting the table object directly. If relations are set between other tables, it might throw this error.
Rather, you can create a model class, assign values to the class object and then serialize it.
I'm Using the fix, Because Using Knockout in MVC5 views.
On action
return Json(ModelHelper.GetJsonModel<Core_User>(viewModel));
function
public static TEntity GetJsonModel<TEntity>(TEntity Entity) where TEntity : class
{
TEntity Entity_ = Activator.CreateInstance(typeof(TEntity)) as TEntity;
foreach (var item in Entity.GetType().GetProperties())
{
if (item.PropertyType.ToString().IndexOf("Generic.ICollection") == -1 && item.PropertyType.ToString().IndexOf("SaymenCore.DAL.") == -1)
item.SetValue(Entity_, Entity.GetPropValue(item.Name));
}
return Entity_;
}
You can notice the properties that cause the circular reference. Then you can do something like:
private Object DeCircular(Object object)
{
// Set properties that cause the circular reference to null
return object
}
//first: Create a class as your view model
public class EventViewModel
{
public int Id{get;set}
public string Property1{get;set;}
public string Property2{get;set;}
}
//then from your method
[HttpGet]
public async Task<ActionResult> GetEvent()
{
var events = await db.Event.Find(x => x.ID != 0);
List<EventViewModel> model = events.Select(event => new EventViewModel(){
Id = event.Id,
Property1 = event.Property1,
Property1 = event.Property2
}).ToList();
return Json(new{ data = model }, JsonRequestBehavior.AllowGet);
}
An easier alternative to solve this problem is to return an string, and format that string to json with JavaScriptSerializer.
public string GetEntityInJson()
{
JavaScriptSerializer j = new JavaScriptSerializer();
var entityList = dataContext.Entitites.Select(x => new { ID = x.ID, AnotherAttribute = x.AnotherAttribute });
return j.Serialize(entityList );
}
It is important the "Select" part, which choose the properties you want in your view. Some object have a reference for the parent. If you do not choose the attributes, the circular reference may appear, if you just take the tables as a whole.
Do not do this:
public string GetEntityInJson()
{
JavaScriptSerializer j = new JavaScriptSerializer();
var entityList = dataContext.Entitites.toList();
return j.Serialize(entityList );
}
Do this instead if you don't want the whole table:
public string GetEntityInJson()
{
JavaScriptSerializer j = new JavaScriptSerializer();
var entityList = dataContext.Entitites.Select(x => new { ID = x.ID, AnotherAttribute = x.AnotherAttribute });
return j.Serialize(entityList );
}
This helps render a view with less data, just with the attributes you need, and makes your web run faster.
Please Help
This is how i'm updating....
[HttpPost, ActionName("Edit")]
public ActionResult Edit(Students model)
{
if (ModelState.IsValid)
{
using (DbAccess db = new DbAccess())
{
var ID=db.students.Find(model.id);
db.Entry(ID).State = EntityState.Modified;
//ID.name = model.name;
//ID.address = model.address;
//ID.age = model.age;
//ID.email = model.email;
//ID.isActive = model.isActive;
db.SaveChanges();
}
}
return View(model);
}
In the above code when i update separately than it works well but when i use db.Entry(...)...... than it doesn't work for me and it also not shows any error
You can try...
[HttpPost, ActionName("Edit")]
public ActionResult Edit(Students model)
{
if (ModelState.IsValid)
{
using (DbAccess db = new DbAccess())
{
var ID = db.students.Find(model.id);
//db.Entry(ID).State = EntityState.Modified;
ID.name = model.name;
ID.address = model.address;
ID.age = model.age;
ID.email = model.email;
ID.isActive = model.isActive;
db.SaveChanges();
}
}
return View(model);
}
When you are doing var ID=db.students.Find(model.id);
You don't need to use
db.Entry(ID).State = EntityState.Modified;
Because when you do Find you have real object of your dbContext, when you make changes on it(except on it primary key of course), your SaveChanges will detect it and update it accordingly.
You need to set State only when you are doing something like this
Students students = new Students(); //a new object which is not created using `Find`
students.name = "Heartlion";
students.address = "address text";
db.Entry(students).State = EntityState.Modified;
db.SaveChanges();
just replace this:
db.Entry(ID).State = EntityState.Modified;
//ID.name = model.name;
//ID.address = model.address;
//ID.age = model.age;
//ID.email = model.email;
//ID.isActive = model.isActive;
with:
UpdateModel(ID);
and you'll be fine;
In order for your method to work, you need to do like this:
db.Students .Attach(ID);
var entry = db.Entry(ID);
entry.State = EntityState.Modified;
entry.Property(x => x.name).IsModified = true;
entry.Property(x => x.address).IsModified = true;
....
db.SaveChanges();
Basically you need to attach the updated model then to tell to the context, which props are modified.
I have in my repository, another method which I use in some situations, when the update is not done in the controller, the method is:
public void Update(TEntity newEntity)
{
var oldEntity = Context.Set<TEntity>().Find(newEntity.Id);
Context.Entry(oldEntity).CurrentValues.SetValues(newEntity);
}
In this method, the newEntity is comming from the view, and the oldEntity is from the context.
UpdateModel can be used only in controllers, when I call the update outside of the controller, I use the above method. I prefer this methods because I do not need to explicitly tell which props are been modified. When you have a form with 10 props, and user is updating only 3 or 4, you need a lot of logic to determine which were modified.
PS - my entities are all implementing IEntityId, which is an interface with common properties, like Id, UpdateDate, InsertDate ..., this is why I can call newEntity.Id
I am trying to add comments to a topic selected from a list of topics created,
I have a list of topics and I select one of them..
the selected topic loads its view with its comments due to the id of the topic.
On the selected topic view, I want to add a comment, so on post of the comment, it adds the comment(in the table) but can't return or redirect to view (topics with comments) because that view is as a result of that topic id.
so am looking for a way whereby its returns back to the view after adding a comment with the id of the topic view...
or is there another way of solving this,,..
I really need assistance here...
this is the error i get
Server Error in '/' Application.
The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'TechForum.Models.ForumViewModel'.
below is my code that loads the comments in a topic....
The 'int id' is the id of the topic from a list of topics
[HttpGet]
public ActionResult Comments(ForumViewModel model, int id)
{
DataSet ds = WebService.GetCommentsByTopic(id);
List<CommentModel> commentModelList = new List<CommentModel>();
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
CommentModel _commentModel = new CommentModel();
_commentModel.COMMENTID = Int32.Parse(dr["COMMENTID"].ToString());
_commentModel.TOPICID = Int32.Parse(dr["TOPICID"].ToString());
Session["topicid"] = Int32.Parse(dr["TOPICID"].ToString());
_commentModel.COMMENT = dr["COMMENT"].ToString();
_commentModel.COMMENT_DATE = DateTime.Parse(dr["COMMENT_DATE"].ToString());
commentModelList.Add(_commentModel);
}
model.COMMENTLIST = commentModelList;
return View(model);
}
below is the code for adding comments
I tried passing the topic id from the httpget comment view to the post comment through a session
[HttpPost]
public ActionResult Comments(ForumViewModel model)
{
try
{
WebService.AddComment(int.Parse(Session["memberid"].ToString()), int.Parse(Session["topicid"].ToString()), model.COMMENTS.COMMENT, DateTime.Parse(model.COMMENTS.COMMENT_DATE.ToString()));
int id = int.Parse(Session["topicid"].ToString());
ViewData["output"] = "Comment Added";
return View("Comments", id);
}
catch (Exception er)
{
ViewBag.errormsg = er.Message;
ViewData["output"] = "Comment not added";
}
return RedirectToAction("Comment", int.Parse(Session["topicid"].ToString()));
}
the same similar issue for the delete of which I tried passing two id's to the view as shown below, one to take the id of the comment its about to delete and the other (id2) to send back the id of the topic to the view
#Html.ActionLink("x", "DeleteComment", new { id = item.COMMENTID, id2 = item.TOPICID}
below is the delete action
public ActionResult DeleteComment(int id, int id2)
{
WebService.DeleteComment(id);
ForumViewModel model = new ForumViewModel();
DataSet ds = WebService.GetCommentsByTopic(id2);
List<CommentModel> commentModelList = new List<CommentModel>();
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
CommentModel _commentModel = new CommentModel();
_commentModel.COMMENTID = Int32.Parse(dr["COMMENTID"].ToString());
_commentModel.TOPICID = Int32.Parse(dr["TOPICID"].ToString());
_commentModel.MEMBERID = Int32.Parse(dr["MEMBERID"].ToString());
_commentModel.COMMENT = dr["COMMENT"].ToString();
_commentModel.COMMENT_DATE = DateTime.Parse(dr["COMMENT_DATE"].ToString());
commentModelList.Add(_commentModel);
}
model.COMMENTLIST = commentModelList;
ViewData["success"] = "Comment Deleted";
return RedirectToAction("Comments", model);
}
Can you just put the TopicId in the ForumViewModel and have it as a hidden field in the view that is set to what you want so it is passed around in the model. Can't see why that wouldn't work.
Im learning MVC 4. I have created a database first project using EF5. In my edit view I want to add a product number to a customer. When I hit save I get the message below. I think it is because product number is null in the product table, hence it cannot update. Can I get around this? I have added my edit control
public ActionResult Edit(int id = 0)
{
UserProfile userprofile = db.UserProfiles.Find(id);
if (userprofile == null)
{
return HttpNotFound();
}
//ViewBag.userId = new SelectList(db.Devices, "DeviceID", "DeviceIMEI", userprofile.UserId);THIS CREATES A NEW ENTRY IN USERPROFILE TABLE
ViewBag.Device_DeviceID = new SelectList(db.Devices, "DeviceID", "DeviceIMEI", userprofile.Device);
ViewBag.ShippingDetails_ShippingDetailsID = new SelectList(db.ShippingDetails, "ShippingDetailsID", "Address1", userprofile.ShippingDetails_ShippingDetailsID);
return View(userprofile);
}
//
// POST: /User/Edit/5
[HttpPost]
public ActionResult Edit(UserProfile userprofile)
{
if (ModelState.IsValid)
{
db.Entry(userprofile).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
//ViewBag.userId = new SelectList(db.Devices, "DeviceID", "DeviceIMEI", userprofile.UserId);
ViewBag.Device_DeviceID = new SelectList(db.Devices, "DeviceID", "DeviceIMEI", userprofile.Device);
ViewBag.ShippingDetails_ShippingDetailsID = new SelectList(db.ShippingDetails, "ShippingDetailsID", "Address1", userprofile.ShippingDetails_ShippingDetailsID);
return View(userprofile);
}
"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries"
It looks like you dont pass Id of UserProfile from
view to controller.
You should add
#Html.HiddenFor(model => model.Id)
to your form in view
You're posting a view model, which is disconnected from your entity framework, and trying to tell the EF that it has changed -- which it doesn't know about. Try something like this instead,
var obj = yourContext.UserProfiles.Single(q=>q.Id==userProfile.Id);
obj = userprofile; // ... Map userprofile to the tracked object, obj
yourContext.SaveChanges();
Try this:
if (ModelState.IsValid)
{
db.UserProfiles.Attach(userProfile);
db.SaveChanges();
return RedirectToAction("Index");
}
I'm using the latest Asp.Net MVC version.
For some reason, when my POST (Action Create) in my controller gets hit.
I can't seem to be able to add it to the entityset.
What i have is,
1) My EntityModel (*.edmx file)
2) Controller which references the entity:
private db.DataContainer _db = new db.DataContainer();
3) My method (i'm using Guid as pk):
[HttpPost]
public ActionResult Create(Client client)
{
try
{
client.Id = Guid.NewGuid();
/* method 2
Client cl = new Client();
cl.Id = Guid.NewGuid();
cl.email = client.email;
cl.Adres = client.Adres;
cl.companyName = client.companyName;
cl.fax = client.fax;
cl.phone = client.phone;
*/
// client.Id = Guid.NewGuid();
_db.ClientSet.AddObject(client);
_db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
var ex_message = ex.Message;
var ex_data = ex.Data;
var ex_ix = ex.InnerException;
return View();
}
}
4) Following is my InnerException:
[System.Data.SqlClient.SqlException] = {"Cannot insert the value NULL into column 'Id', table 'lst.dbo.ClientSet'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
Both doesn't seem to work :(
GUIDs are not supported as primary keys in the Entity Framework. You will need to modify your save method to generate a new GUID for your added objects http://msdn.microsoft.com/en-us/library/dd283139.aspx
It seems that changing my "saveCommand" has given my a temporarily solution:
I chaned:
_db.SaveChanges()
To
_db.SaveChanges(System.Data.Objects.SaveOptions.None);