Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs mapping from/to POCO object

Is there a way to map from/to a POCO and knockoutjs observable?

I have a Note class:

public class Note
{
    public int ID { get; set; }
    public string Date { get; set; }
    public string Content { get; set; }
    public string Category { get; set; }
    public string Background { get; set; }
    public string Color { get; set; }
}

and this is my javascript:

$(function () {
    ko.applyBindings(new viewModel());
});

function note(date, content, category, color, background) {
    this.date = date;
    this.content = content;
    this.category = category;
    this.color = color;
    this.background = background;
}

function viewModel () {
    this.notes = ko.observableArray([]);
    this.newNoteContent = ko.observable();

    this.save = function (note) {
        $.ajax({
                url: '@Url.Action("AddNote")',
                data: ko.toJSON({ nota: note }),
                type: "post",
                contentType: "json",
                success: function(result) { }

            });
    }

    var self = this;
    $.ajax({
        url: '@Url.Action("GetNotes")',
        type: "get",
        contentType: "json",
        async: false,
        success: function (data) {
            var mappedNotes = $.map(data, function (item) {
                return new note(item.Date, item.Content, item.Category, item.Color, item.Background);
            });
            self.notes(mappedNotes);
        }
    });
}

Ignore the fact that the save function is not used (to simplify the code here).

So, when I load the page I call the server and I retrieve a list of Note objects and I map it in javascript. Notice how ID is not mapped because I dont need it in my view.

So far so good, I see the notes on screen, but how I can save the notes back to the server?

I tried to convert the note (Im saving just the new note and not the entire collection) to JSON and send it to my controller but I don't know how to access to the note in the controller. I tried:

    public string AddNote(string date, string content, string category, string background, string color)
    {
        // TODO
    }

but is not working. I want to have something like:

public string AddNote(Note note) {}

(Btw, what's the best return for a method that just save data on DB? void?)

So, How I do this? I tried knockout.mapping plugin but it is quite confusing and I don't get it working for me.

Thank you.

like image 509
Jesus Rodriguez Avatar asked Aug 02 '11 12:08

Jesus Rodriguez


1 Answers

ASP.NET MVC's model binder will look for properties that are case-sensitive. You need to pass your JSON object back to the server with the property names matching your poco object.

I usually do 1 of 2 things:

  1. Make my javascript object property names capital (that way in JS, I know that this object will at some point be a DTO for the server)

    function Note(date, content, category, color, background) {
        this.Date = date;
        this.Content = content;
        this.Category = category;
        this.Color = color;
        this.Background = background;
    };
    
  2. In my AJAX call i will just create an anonymous object to pass back to the server (note this does not require ko.toJSON):

    $.ajax({
            url: '@Url.Action("AddNote")',
            data: JSON.stringify({ note: {
                    Date: note.date,
                    Content: note.content,
                    Category: note.category,
                    Color: note.color,
                    Background: note.background
                    }
                }),
            type: "post",
            contentType: "application/json; charset=utf-8",
            success: function(result) { }
    });
    

    (note the different contentType parameter as well)

You will want to make your ActionMethod take in a (Note note) and not just the array of parameters.

Also, because the modelbinders look through the posted values in a couple different ways. I've had luck posting JSON objects with out specifying the ActionMethod parameter name: instead of:

    { note: {
        Date: note.date,
        Content: note.content,
        Category: note.category,
        Color: note.color,
        Background: note.background
        }
    }

just do:

    {
        Date: note.date,
        Content: note.content,
        Category: note.category,
        Color: note.color,
        Background: note.background
    }

(but this can get dicey with arrays binding to collections and complex types...etc)

As far as the 'Best' signature for a return on a method that does a db call, we generally prefer to see boolean, but that also depends on your needs. Obviously if it is trivial data, void will be fine, but if its a bit more critical, you may want to relay a boolean (at the least) to let your client know it might need to retry (especially if there's a concurrency exception).

If you really need to let your client know what happened in the database, you can foray into the world of custom error handling and exception catching.

Also, if you need to display very specific information back to your user depending upon a successful/unsuccessful database commit, then you could look at creating custom ActionResults that redirect to certain views based upon what happened in the database transaction.

Lastly, as far as getting data back from the server and using Knockout...

  1. again the mapping plugin will work if your property names are the same case or you create a slightly more explicit mapping
  2. My own trick with my JS objects is below. The initialize function is something i created that should be reusable across all your objects as it just says "if the property names match (after being lowercased), either set them by calling the function (knockout compatible) or just assign the value.:

    function Note(values){ //values are what just came back from the server
        this.date;
        this.content;
        this.category;
        this.color;
        this.background;
    
        initialize(values); //call the prototyped function at the bottom of the constructor
    };
    
    Note.prototype.initialize = function(values){
        var entity = this; //so we don't get confused
            var prop = '';
            if (values) {
                for (prop in values) {
                    if (values.hasOwnProperty(prop.toLowerCase()) && entity.hasOwnProperty(prop.toLowerCase())) {
                        //the setter should have the same name as the property on the values object
    
                        if (typeof (entity[prop]) === 'function') {
                            entity[prop](values[prop]); // we are assuming that the setter only takes one param like a Knockout observable()
                        } else {// if its not a function, then we will just set the value and overwrite whatever it was previously
                            entity[prop] = values[prop];
                        }
                    }
                }
            }
    };
    
like image 62
ericb Avatar answered Oct 24 '22 00:10

ericb