【问题标题】:Mvc and konckout: click data bind won't redirect to another actionMvc 和 konckout:单击数据绑定不会重定向到另一个操作
【发布时间】:2014-10-26 00:54:13
【问题描述】:

我希望在 foreach 循环列表中包含指向 MyAction 的链接的 href 标签。

在 Edit.cshtml (http://localhost/mysite/Order/Edit/4) foreach 循环(淘汰赛)中,每个项目都有一个 href:

<a href="#" data-bind="click: $parent.EditForStore">Eddit</a>

方法在 ViewModel.js 中实现:

self.EditForStore  = function (item) {
        console.log(item.IdStore());
        var idStore = item.IdStore();

        //var urlMeta = '@Url.Action("MyAction", "MyController", new { pStoreId = ' + idStore.toString() + ' })';

        var urlMeta = '@Url.Action("MyAction", "MyController", new { pStoreId = 4 })';

        //var myURL = '@Url.Action("MyAction", "MyController")';
        window.location.href = urlMeta;
    };

我无法重定向到 MyAction。 当我设置 location.href 时,它会重定向到 http 地址:

http://localhost/mysite/Order/Edit/4/MyAction/MyController?pStoreId=4

我无法更改 location.href,我只能将文本附加到我当前的地址。

【问题讨论】:

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


【解决方案1】:

我用来让服务器端路由进入淘汰赛的技术是生成具有已知参数值的路由并将其存储为数据属性。然后敲除然后将数据值推送到href中。

您可以利用 $element 上下文变量将当前元素提供给在 foreach 绑定中声明在父视图模型上的函数,使用 attr 绑定更新 href 属性。

例如...


HTML

<div data-bind="foreach: stores">
    <a href="#" data-url='@Url.Action("MyAction", "MyController", new { pStoreId = 0 }' data-bind="attr: { 'href' :  $parent.buildUrl($element, id) }, text: id"></a>
</div>

Javascript

var ViewModel = (function() {
    var ctor = function ViewModel() {
        this.stores = ko.observableArray( [{ id: 1 }, {id:2}, {id:3}, {id:4} ]);
    };

    ctor.prototype.buildUrl = function(element, data) {
        return element.getAttribute('data-url').replace('pStoreId=0', 'pStoreId=' + data);
    };
    return ctor;
})();

ko.applyBindings( new ViewModel() );

有关示例,请参阅 http://jsfiddle.net/9Lz4493d/(没有 razor 语法和硬编码的 data-url 属性,但你明白了。)

Url builder 函数可以轻松增强以提供参数名称等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 2015-03-03
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多