Reputation: 767
I know how to get data in json format from my MVC application (see below)
public JsonResult Index()
{
return Json(db.Publications, JsonRequestBehavior.AllowGet);
}
What would the create method look like? Edit?
I'm guessing it would look something like the following
[HttpPost]
public void Create(Publication publication)
{
try
{
db.Publications.Add(publication);
db.SaveChanges();
}
catch
{
// what do I catch?
}
}
If that is the case, what would my JSON call look like?
(Assuming the Publication class looks like the following)
public class Publication
{
public int Id { get; set; }
public String Title { get; set; }
}
Any help is appreciated.
Upvotes: 0
Views: 191
Reputation: 8639
For the Index, you will probably get some exceptions since the EF objects have a lot of properties that you won't need in the client side and will throw circular references exceptions.
You will have to either create a new POCO class to "wrap" the entities returned by the repository or simply use an anonymous object as suggested here:
Serialize Entity Framework objects into JSON
i.e.:
return Json(db.Publications.Select(p => new {Id = p.Id, Title = p.Title}), JsonRequestBehavior.AllowGet);
Then, the call using Json from the client will have to look like this (assuming you are using JQuery):
$.post('/controller/create', {id:$('#idField').val(), name:$('#nameField').val()}, function(){alert('Publication created');});
Hope this helps
Upvotes: 1