Search code examples
javascriptc#asp.net-mvcknockout.jsknockout-mapping-plugin

Knockout.js get property of an object for location.href


i recently discover Knockout and i'm struggling for getting properties of an object in a foreach:

Here is my code :

<table class="table">
<thead>
    <tr>
        <th>Name</th>
        <th>Created By</th>
    </tr>
</thead>
<tbody data-bind="foreach: assets">
    <tr class="assets" data-bind="click: $parent.detailPage">
        <td>
            <span data-bind="text: FileName"></span>
        </td>
        <td>
            <span data-bind="text: CreatedBy"></span>
        </td>
    </tr>
</tbody>

and my script :

<script>
function ViewModel(assets) {
    var self = this;

    self.assets = assets;

    self.detailPage = function (asset) {
        location.href = '@Url.Action("Details", "Assets")/' + asset.Id;
    };
};

var jsonModel = new ViewModel(@Html.Raw(Json.Encode(Model)));
var viewModel = ko.mapping.fromJS(jsonModel);
ko.applyBindings(viewModel);

In my assets, i have an id and i would like to open my view using the id of the object i click on.

But when i execute that, the url become : http://localhost:62677/Assets/Details/[object Object]

Any idee for doing this properly ?

Thanks !


Solution

  • Assuming that asset.Id is a knockout observable, try this

    self.detailPage = function (asset) {
            location.href = '@Url.Action("Details", "Assets")/' + asset.Id();
        };