I'm creating a simple mvc web api demo as follows.
```c#
[HttpPut("{id}")]
public async void Put(int id, [FromBody]Student student)
{
if (ModelState.IsValid)
{
var stu = _context.Students
.Where(s => s.StudentId == id)
.SingleOrDefault();
var updateResult = await TryUpdateModelAsync<Student>(stu, "", s => s.FirstName, s => s.LastName, s => s.EnrollmentDate);
_context.SaveChanges();
}
}
The HTTP request to test the method is:
```json
PUT /api/Student/2 HTTP/1.1
Host: localhost:5207
Content-Type: application/json
Cache-Control: no-cache
{
"studentId": 2,
"firstName": "Tony",
"lastName": "Black",
"enrollmentDate": "2016-12-21T00:00:00"
}
The problem is that TryUpdateModelAsync doesn't work, no properties in stu object got updated with corresponding properties from student object (the incoming parameter).
I wonder:
c#
stu.FirstName = student.FirstName;
stu.LastName = student.LastName;
stu.SomeOtherProperties = student.SomeOtherProperties;
_context.SaveChanges();
.NET Core version: 1.1.0 ASP.Net Core version: 1.1.0 Entity Framework Core version: 1.1.0
The [FromBody]
attribute uses formatters to deserialize the request body into an object (e.g. using JSON or XML).
On the other hand, model binding, which includes the TryUpdateModel
API, uses value providers to get data from the form body (if any), query string, route data, or some other places.
There are a few ways to go here:
Thanks for the thorough suggestions, I am gonna go with the 3rd option.
One of big benefits of open source project is that we can directly communicate with the Dev teams, skipping the first line of support who seems not touch the core of the product. I really liked this way of interaction and support model. Thank you again.
Thanks for your kind comments!
Most helpful comment
Thanks for the thorough suggestions, I am gonna go with the 3rd option.
One of big benefits of open source project is that we can directly communicate with the Dev teams, skipping the first line of support who seems not touch the core of the product. I really liked this way of interaction and support model. Thank you again.