Sending model data from knockout back to MVC 3

I am new to knockout and have difficulty trying to get my Knockout data back to my server. I keep getting the "No parameterless constructor defined for this object" error. Any help would be appreciated.

My knockout model is as follows

function partSummary(item) { var self = this; self.ID = ko.observable(item.ID); self.serialNumber = ko.observable(item.SerialNumber); self.description = ko.observable(item.Description); self.manufacturer = ko.observable(item.Manufacturer); self.creationDate = ko.observable(item.DateCreated); self.active = ko.observable(item.IsActive); } 

My code to send data back to the server

 self.savePart = function() { $.ajax("/PartKO/UpdatePart", { data: ko.toJSON(self.partDetails), type: "post", contentType: 'application/json', dataType: 'json' }); }; 

My MVC

 [HttpPost] public JsonResult UpdatePart(PartDetail part) { var dbPart = new PartGenericAccessor(); dbPart.ID = part.ID; dbPart.Load(); dbPart.Description = part.Description; dbPart.IsActive = Convert.ToBoolean(part.IsActive); var manufacturers = ManufacturerAccessor.LoadAll<ManufacturerAccessor>(); if (part.Manufacturer != null) { var manufacturer = (from p in manufacturers where p.Name == part.Manufacturer select p.ID).First(); dbPart.ManufacturerID = manufacturer; } dbPart.Save(); return Json("Success!!"); } 

And my server side model

  public class PartDetail { public PartDetail(Guid id, string serial, string description, string manufacturer, DateTime created, bool isActive) { ID = id; SerialNumber = serial; Description = description; Manufacturer = manufacturer; DateCreated = created.ToShortDateString(); IsActive = isActive.ToString(CultureInfo.InvariantCulture); } public Guid ID { get; set; } public string SerialNumber { get; set; } public string Description { get; set; } public string Manufacturer { get; set; } public string DateCreated { get; set; } public string IsActive { get; set; } } 
+6
source share
2 answers

You need to provide a parameterless constructor for your MVC model:

 public class PartDetail { public PartDetail() { ... } } 

When data is returned from the server, MVC will create an empty object using the constructor without parameters, and then call the "set" methods to set each property that matches the incoming data.

+5
source

As soon as I made a dumb mistake:

The controller's named argument is "action" - and in the column it is always null.

 [HttpPost] public JsonResult AddMetaAction(ActionModel action) 

I did not know about it and spend on debugging and solving this problem in about half an hour :(

0
source

Source: https://habr.com/ru/post/905538/


All Articles