Displaying data mapping with knockoutjs

I am having problems binding the selected value of a selectbox to a property in a view model. For some reason, it keeps coming back unchanged when posted back to the server.

My Html:

<form action="/Task/Create" data-bind="submit: save"> 

    <table border="1">
            <td>ref type</td>
            <td><select data-bind="options: ReferenceTypes, optionsText: 'Name', optionsCaption: 'Select...', value:Task.ReferenceTypeId"></select></td>
            <td><input data-bind="value:Task.Reference" /></td>

    <button type="submit">Save Listings</button> 



<script type="text/javascript">

    var viewModel = {};

    $.getJSON('/Task/CreateJson', function (result) {
        viewModel = ko.mapping.fromJS(result.Data);

        viewModel.save = function () {
            var data = ko.toJSON(this);
                url: '/Task/Create',
                contentType: 'application/json',
                type: "POST",
                data: data,
                dataType: 'json',
                success: function (result) {
                    ko.mapping.updateFromJS(viewModel, result);




JSON from Fiddler that is loaded into the page as shown below.

         "Reference":"Default Value"
           "Name":"A Ref Type"
            "Name":"B Ref Type"
            "Name":"C Ref Type"


This returns to the server (ASP.NET MVC3) correctly, with the updated reference string value, but the ReferenceTypeId is not tied to the correctly selected dropdown value. Do I need to do any additional functionality for correct binding, etc.? Or tell the data binding to which column of the select value (Id), etc.? I checked in Fiddler the values ​​sent back from the browser and it has the same original value (0). So it is definitely not a server.

I hope someone can help, if you need more information please ask.

Regards, Phil


source to share

1 answer

The problem is that your binding options

will try to assign the object it is bound to to the specified value observable


For example if you select "A Ref Type" the binding options

will push the json object

{ "Id":2, "Name":"A Ref Type" }


Into your Task.ReferenceTypeId observable, which will then be serialized back to your server. In this case, you need to add optionsValue config options to specify the binding to only store the id.

<select data-bind="options: ReferenceTypes, optionsText: 'Name', 
optionsCaption: 'Select...', optionsValue: 'Id', value:Task.ReferenceTypeId">


Here's an example.


Hope it helps.



All Articles