Partial upgrade using asp.net web api

I created a simple to-do list application in asp.net mvc 3 with web api and dbContext. (with foundation and requirejs for the client) Everything works fine, but I'm kind of concerned about the fact that I need to send the entire model to the server if I check or uncheck how to do this. I would only like to send the "done" field when sending the data.

I should mention that I also use JsonNetFormatter to use JSON.NET as a standard Serializer (explained here: http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net- with-asp-net-web-api.aspx ).

This is currently my api controller method for updating the model

public HttpResponseMessage Put(Todo todo) { _db.Entry(todo).State = EntityState.Modified; _db.SaveChanges(); return new HttpResponseMessage(HttpStatusCode.NoContent); } 

It takes this as json data

 {"content":"Pick up milk","done":false,"id":10} 

Of course, this works, but it updates the whole model, it should update only one field. I can only achieve sending the changed fields to the server from the browser, but I'm not sure what the web api method should look like. I was thinking about doing something with FormCollection, but this does not seem to work with the web api, since it seems to be trying to serialize the passed formal values โ€‹โ€‹directly to the FormCollection type, I get this error.

 Cannot deserialize JSON object (ie {"name":"value"}) into type 'System.Web.Mvc.FormCollection'. 

How can I send a partial update for 1 or more fields from a model to my web api? I just want to send the updated fields to the server, and from there only update these fields in the database. Of course, I do not want to query the database before updating.

+8
c # asp.net-mvc asp.net-web-api
source share
2 answers

One approach would be to use the Automapper tool and set it up so that null values โ€‹โ€‹do not overwrite existing ones when matching Todo. For example:

  Mapper.CreateMap<Todo,Todo>() .ForMember(d => d.Id, o => o.Ignore()) .ForAllMembers(mo => mo.Condition(cond => !cond.IsSourceValueNull)); 

Then you just need to match the obtained value of the object with the existing one, for example:

  Mapper.Map(todo, item); 

Another suggestion is to use PATCH instead of PUT, which is more suitable for partially updating resources in accordance with REST .

+2
source share

You need to query the source object from the database, set its properties and call _db.SaveChange ()

 public HttpResponseMessage Put(Todo todo){ var item = _db.Todo.First(i => i.id = todo.id); item.Content = todo.Content; item.Done = todo.Done; _db.SaveChanges(); return new HttpResponseMessage<Todo>(HttpStatusCode.Accepted); } 

Ref .: http://msdn.microsoft.com/en-us/library/dd456854.aspx

-3
source share

All Articles