knockout.js在视图模型中重定向

时间:2013-05-24 12:40:18

标签: asp.net-mvc razor knockout.js

我在cshtml页面上有以下代码。

 <div class="buttons">
    <button type="button" id="export" class="export-inventory-button" onclick="location.href='@Url.Action("ExportInventory", "Inventory")'">EXPORT INVENTORY</button>
</div>

如何在我的视图模型中完成此工作?

我想我差不多了,但需要一些帮助

<div class="buttons">
    <button type="button" id="export" class="export-inventory-button" data-bind="click: exportInventory">EXPORT INVENTORY</button>
</div>

我的viewmodel有这段代码:

 function exportInventory() {
                filtererGridData = vm.details;

                var json = ko.mapping.toJSON(vm.details);

                $.ajax({ url: '/Inventory/ExportInventory', type: 'POST' }).done(function (data) {
                    $('#export').html(data);
                }).fail(function (data) {
                    toastr.warn('Could not export data, please contact LGL.');
                });
            }

我尝试了这个,但是我收到了错误:

function exportInventory() {
                filtererGridData = vm.details;

                var json = ko.mapping.toJSON(vm.details);

                $.ajax({ url: 'location.href="@Url.Action("ExportInventory", "Inventory")"', type: 'POST' }).done(function (data) {
                    window.location.href = responseText.url;
                    $('#export').html(data);
                }).fail(function (data) {
                    toastr.warn('Could not export data, please contact LGL.');
                });
            }

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您尝试将网址传递给ajax调用的方式可能与您预期的方式不同。此外,您不需要location.href=成为$.ajax()来电中url参数的一部分。

如果你的视图模型在cshtml页面的脚本标签中编码,你可以试试这个:

<!-- cshtml razor view code for generating the html is above this line -->

<script>
    var viewModel = {
        function exportInventory() {
            filtererGridData = vm.details;

            var json = ko.mapping.toJSON(vm.details);

            //allow razor to build a javascript string for you when it renders the html
            //when the browser parses this script, it will just see a simple string
            var myURL = '@Url.Action("ExportINventory", "Inventory")';

            //pass your variable to the jQuery ajax call
            $.ajax({ url: myURL, type: 'POST' }).done(function (data) {
                window.location.href = responseText.url;
                //this line of code would never be called because the browser has navigated away from this page...
                $('#export').html(data);
            }).fail(function (data) {
                toastr.warn('Could not export data, please contact LGL.');
            });
        }
    };
</script>

加载页面并查看源代码。如果var myUrl =行是控制器的正确URL作为字符串,那么你就知道剃刀已经开始并为你准备渲染。