Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending model data from Knockout back to MVC 3

I am new to knockout and am having a hard time trying to get my data from Knockout back to my server. I keep getting an error of 'No parameterless constructor defined for this object.' 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 the data back the server is

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

My MVC controller is

[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 is

    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; }
}
like image 284
PlTaylor Avatar asked Jan 09 '12 16:01

PlTaylor


1 Answers

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

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

When the data comes back from the server, MVC will create an empty object, using the parameterless constructor and then call the 'set' methods to set each property that matches the data coming in.

like image 84
Mark Robinson Avatar answered Sep 29 '22 20:09

Mark Robinson