I have the following situation, a Person class, with Id properties, Name, Birth, I want to implement a page that can update only the Person Name. My implementation should get a person by their Id, and change only the Name field.
I did the below implementation in MVC, but how could I do the same with WebApi, since I do not have the TryUpdateModel or UpdateModel. Implement functionality with this routine to make it easier to generalize in the future.
Controller code in MVC:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult SetNome()
{
var sample = Pessoa.FindById(12);
TryUpdateModel<Pessoa>(sample);
return Json("sucesso");
}
}
public class Pessoa
{
[Required]
public int Id { get; set; }
[Required]
public string Nome { get; set; }
[Required]
public DateTime? Nascimento { get; set; }
public static Pessoa FindById(int id)
{
return new Pessoa() { Id = 12, Nome = "Meu Nome", Nascimento = Convert.ToDateTime("1989-01-31") };
}
}
View Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.angularjs.org/1.4.3/angular.js"></script><script>varapp=angular.module("MainModule", []);
var MainController = function ($scope, $http) {
var url = 'http://localhost:47107/home/setnome';
//var url = 'http://localhost:47107/api/values';
$scope.pessoa = {};
$scope.pessoa.nome = "xpto";
$scope.enviar = function () {
$http({
url: url,
method: "POST",
data: $scope.pessoa
})
.then(function (response) {
// success
console.log(JSON.stringify(response));
},
function (response) {
// failed
console.log(JSON.stringify(response));
});
}
};
app.controller("MainController", MainController);
</script>
</head>
<body ng-app="MainModule">
<div ng-controller="MainController">
<input id="pessoa.nome" ng-model="pessoa.nome" />
{{pessoa.nome}}
<button ng-click="enviar()">Enviar</button>
</div>
</body>
</html>
Current code in WebApi:
public class ValuesController : ApiController
{
public void Post([FromBody]Pessoa pessoa)
{
var sample = Pessoa.FindById(12);
sample.Nome = pessoa.Nome;
}
}
I'd like to have to abstract the fill of the Name field, as it did in the MVC, with the UpdateModel, it identifies which fields were sent by View and only fill them, the others it keeps original. With WebApi I have to do this manually.