简体   繁体   English

如何与Razor和Knockout进行数据绑定

[英]How to data-bind with Razor and Knockout

I'm trying to set a Knockout-bound function's parameter with Razor. 我正在尝试使用Razor设置一个Knockout绑定函数的参数。 I've tried... 我试过了...

<a href="#" data-bind="click: function() { return myFunc(@Type.SomeType.ToString()); }">
    Click Me
</a>

and.. 和..

<a href="#" data-bind="click: function() { return myFunc(@Html.Raw(Type.SomeType.ToString())); }">
    Click Me
</a>

and.. 和..

<a href="#" data-bind="click: function() { return myFunc('@Html.Raw(Type.SomeType.ToString())'); }">
    Click Me
</a>

and.. 和..

<a href="#" data-bind="click: function() { return myFunc('@(Html.Raw(Type.SomeType.ToString()))'); }">
    Click Me
</a>

Is there a right way to do this? 有正确的方法吗?

(Background: this is for use in a bootstrap dropdown) (背景:这是在引导下拉菜单中使用的)

You can try to surround data-bind attribute with single quotes ( ' ) and pass the parameter using Json.Encode . 您可以尝试将data-bind属性用单引号( ' )括起来,并使用Json.Encode传递参数。

Full example: 完整示例:

@{
    // A string with a lot of special characters
    string myStr = "abc\"\\/'#{}@.:xyz";
}

<span data-bind='click: function() { myFunc(@Json.Encode(myStr)); }'>
    Click Me
</span>

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-debug.js"></script>
<script>
    ko.applyBindings({
        myFunc: function (myParam) {
            console.log(myParam);
        }
    });
</script>

In your case it would be: 您的情况是:

<a href="#" data-bind='click: function() { return myFunc(@Json.Encode(Type.SomeType.ToString())); }'>
    Click Me
</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM