2016-12-08 24 views
0

我是新來的淘汰賽,並且在MVC標記中使用它時遇到了語法問題。我想用Knockout來使用Url.Action

例如,這裏的代碼;

<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> 

編輯 那麼「答案」是在視圖模型,並在淘汰賽您可以鍵入數據綁定=「文本:答案」,但在這裏我已經把2個地方text.Answer。如何替換text.Answer在上面的代碼中使用正確的Knockout標記?

我知道上面的代碼不起作用,但這是顯示問題的簡化方式。我想要將數據綁定到text.Answer。這樣做的正確語法是什麼?

+0

您需要更詳細地描述您的問題。有沒有敲你的代碼特定的。是問題? – TryingToImprove

+0

我編輯了這個問題。我希望現在更有意義? – arame3333

回答

0

我猜你有綁定到DOM的這部分視圖模型,所以你應該能夠使用data-bind屬性和attr結合實現以下目標:

<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;" /> 
+0

你猜對了。我看到我的問題並不清楚,所以我編輯了它。你已經爲超鏈接做出了迴應,而且看起來不錯。 text.Answer也在Url.Action命令中。如果你能解決這個問題,我將非常感激。 – arame3333

+0

更新的答案,你應該現在在viewmodel中生成你的img src,因爲這會讓更多的客戶端擔心。 –

0

如果我的理解是否正確,你的text.Answer是在客戶端的東西綁定。

你不能用客戶端變量混合@Url.Action

嘗試創建URL這樣

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

0

你可以通過你需要到視圖模型中的值。

<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>