Asp.net mvc 4 Mvc和konckout:单击数据绑定赢得';不要重定向到另一个操作

Asp.net mvc 4 Mvc和konckout:单击数据绑定赢得';不要重定向到另一个操作,asp.net-mvc-4,knockout.js,Asp.net Mvc 4,Knockout.js,我希望在foreach循环中有a href标签列表,其中包含指向MyAction的链接 在Edit.cshtml(http://localhost/mysite/Order/Edit/4)在foreach循环(淘汰)中,我为每个项目都有一个href: <a href="#" data-bind="click: $parent.EditForStore">Eddit</a> 我无法重定向到我的操作。 当我设置location.href时,它重定向到http地址: http

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

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

<a href="#" data-bind="click: $parent.EditForStore">Eddit</a>
我无法重定向到我的操作。 当我设置location.href时,它重定向到http地址:

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

我无法更改位置。href,我只在我的当前地址中添加文本。

我用于将服务器端路由转换为淘汰的一种技术是使用已知参数值生成路由,并将其存储为数据属性。然后knockout将数据值推送到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>
请参阅以获取示例(没有razor语法和硬编码的数据url属性,但您已经了解了这一点。)


Url生成器功能可以很容易地进行增强,以提供参数名称等。

在设置窗口之前,您能否注销
urlMeta
中的内容。位置?在urlMeta is中,当我设置location.href时,它会将我重定向到您使用的浏览器?如果你在不同的浏览器中尝试,你会得到相同的行为吗?Firefox,我将在另一个浏览器上测试browser@Url.Action是Razor语法,需要在cshtml文件中
<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>
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() );