0

1st web service: (User)

[{id:1, UserName:"Jhon"}]

2nd web service: (Message)

[{id:34, Message:"This is a message 1", UserId:1}, {id:35, Message:"This is a message 2", UserId:1}]

How I can map above two ko.obervableArrays so that I can get UserName("Jhon") in my Message ViewModel on base of UserId.

As you know UserId:1 is foreign key of User.

I want to user Message and UserName something like this.

  • data-bind="text: UserName"

  • data-bind="text: Message"

2
  • Are the two services pulling from completely separate data sources? Are they mapped on the backend? Last, are you using EF or providing your own metadata Commented Jul 15, 2013 at 14:44
  • Both web services are coming from same data source. Yes I am user EF and MVC Web API. Commented Jul 15, 2013 at 15:02

2 Answers 2

2

If you used a javascript library like Breeze your life would be much simplified. Without Breeze, you will need to create the model classes in the JavaScript much like you have in your model classes for EF. Basically you will need to maintain a back-end model definition as well as a front-end model definition, and make sure they match.

I would highly recommend looking at breezejs.com as I cannot stress enough how much easier this will make your life. Breeze can inherit your metadata from your EF datacontext and map everything properly from the start, it works hand in hand with knockout, and it will save you weeks of development.

If you want you can also use the Knockout mapping plugin Using Knockout mapping for complex JSON

Sign up to request clarification or add additional context in comments.

2 Comments

I already heard about BreezeJS, it is good. I will read more about this framework. Thanks
@beauXjames Knockout and Breeze have two completely separate area of concerns, they don't overlap at all, and actually work extremely well together. Not sure where or how you have formulated your opinion but it is obviously not well informed and going to make others confused.
1

You could use the create option of the mapping plugin to include the user data, like this: http://jsfiddle.net/H4QfX/

var userData = [{id:1, UserName:"Jhon"}],
    messageData = [{id:34, Message:"This is a message 1", UserId:1}, {id:35, Message:"This is a message 2", UserId:1}];

var users = ko.mapping.fromJS(userData);
var viewModel = ko.mapping.fromJS(messageData, {
    'UserId': {
        create: function(options) {
            return ko.utils.arrayFirst(users(), function(u) {
                if (u.id() == options.data) {
                    return u;
                }
            });
        }
    }});

ko.applyBindings(viewModel);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.