我想在Knockout中使用Url.Action

时间:2016-12-08 11:01:41

标签: asp.net-mvc knockout.js

我是淘汰赛的新手,我在使用MVC标记时遇到了正确的语法问题。

例如这里的代码;

<a href="text.Answer" target="_blank">
    <span style="display:inline-block">
        <img src="@Url.Action("GetPhotoThumbnail", new { path = text.Answer, width = 120, height = 80 })" alt="Property Image" style="margin-top: 5px;" />
    </span>
</a>

EDIT 所以&#34;回答&#34;在ViewModel和淘汰赛中你可以输入data-bind =&#34; text:Answer&#34;但是我在这里放了两个地方的文字。答案。如何替换text.Hnswer在上面的代码中使用正确的Knockout标记?

我知道上面的代码不起作用,但这是显示问题的简化方法。我想数据绑定到text.Answer。这样做的正确语法是什么?

3 个答案:

答案 0 :(得分:0)

我猜你有一个绑定到这部分DOM的视图模型,所以你应该能够使用data-bind属性和attr绑定来实现以下目的: / p>

<a href="" data-bind="attr : { href: text.Answer } " target="_blank">
    <span style="display:inline-block">
        <img src="@Url.Action("GetPhotoThumbnail", new { path = text.Answer, width = 120, height = 80 })" alt="Property Image" style="margin-top: 5px;" />
    </span>
</a>

有关此绑定的详细信息,请参阅http://knockoutjs.com/documentation/attr-binding.html

此外,您还需要让视图模型为您生成img[src]属性值,因此请尝试以下操作:

<img data-bind="attr:{ src: text.answerImgSrc() } " alt="Property Image" style="margin-top: 5px;" />

答案 1 :(得分:0)

如果我理解你的text.Answer在客户端是绑定的。

您不能将@Url.Action与客户端变量混合

尝试像这样创建URL

"@Url.Action("GetPhotoThumbnail")?path="+variable1+"&width="+variable2+"&height=" +variable3

答案 2 :(得分:0)

您可以将所需的值传递给ViewModel。

<div id="test">
    <a href="#" data-bind="attr: { href: href }" target="_blank">
        <span style="display:inline-block">
            <img src="" data-bind="attr: { src: imageUrl }" alt="Property Image" style="margin-top: 5px;" />
        </span>
    </a>
</div>

<script type="text/javascript">
    function MyViewModel(defaultValues) {
        this.href = defaultValues.href;
        this.imageUrl = defaltValues.imageUrl
    }

    var viewModel = new MyViewModel({
        imageUrl: '@Url.Action("GetPhotoThumbnail", new { path = text.Answer, width = 120, height = 80 })',
        href: '@Url.Action("Test")'
    });
    ko.applyBindings(viewModel, document.getElementById('test'));
</script>
相关问题