0

I just wanted to know, what is the elegant way of populating the observable properties after posting json to the server.

my js

var vm = (function() {
  var commit = function(item) {
    var model = {
      Name: item.name(),
      IsActive: item.is_active()
    };

    $.post('/to/server/Post', model);
     .done(function(d) {
       item.id(d.Id);
     });
  }
}());

in my server

public JsonResult Post(itemVm model)
{
  var item = new Item
  {
    Name = model.Name,
    IsActive = model.IsActive
  };
  // do saving here and commit to database
  model.id = item.Id;

  return Json(model, JsonResultBehavior.DenyGet);
}

While above snippet will work. I find it hard to maintain it this way, is there an elegant or another way of doing this? I need the returned Id for update later on.

Btw, I'm using ASP.NET MVC 5, KnockoutJs

Any help would be much appreciated. Thanks

Boy Pasmo
  • 8,021
  • 13
  • 42
  • 67
  • have you considered using knockout mapping http://knockoutjs.com/documentation/plugins-mapping.html ? you can use it to update the client view model with data returned from the server – Sam.C Oct 27 '15 at 15:42
  • yes. but i am having trouble including it in my project. already asked this in SO but still waiting for an answer. perhaps you can answer. it would be a great help. http://stackoverflow.com/questions/33350746/how-to-use-knockoutjs-and-its-available-plugins-with-requirejs – Boy Pasmo Oct 27 '15 at 15:46
  • yes , its tough to maintain @BoyPasmo not so elegant too if there are more properties posted from client. i suggest to try `AutoMapper` at server end & similarly `mapping plugin` to auto generate or map properties at client. – super cool Oct 28 '15 at 07:45
  • @supercool do you think you can show some snippets? – Boy Pasmo Oct 28 '15 at 08:10
  • @BoyPasmo as far `AutoMapper` goes for basic understanding refer this http://www.c-sharpcorner.com/UploadFile/tirthacs/using-automapper-in-mvc/ and for `mapping` at client end refer my old answer http://stackoverflow.com/questions/30910358/mapping-list-with-knockout-mapping/30911392#30911392 . Refer to ko docs on mapping to understand basic things – super cool Oct 28 '15 at 08:36

0 Answers0