Razor / VB.NET で、 JavaScriptの描画 をサーバ側で切り替えるには...
* Razor / VB.NET で、 ビューに記載しているJavaScriptをサーバ側で動的に切り替える方法を記載する。
解決策
* 方法は2つある。(個人的には、「解決策2:@<text>」でいいと思う)* 解決策1:@:
@If Model.IsOn Then
@:<script type="text/javascript">
@: document.getElementById("result").innerText = "Hello!";
@:</script>
Else
@:<script type="text/javascript">
@: document.getElementById("result").innerText = "Good morning!";
@:</script>
End If
* 解決策2:@<text> @If Model.IsOn Then
@<text>
<script type="text/javascript">
document.getElementById("result").innerText = "Hello!";
</script>
</text>
Else
@<text>
<script type="text/javascript">
document.getElementById("result").innerText = "Good morning!";
</script>
</text>
End If
補足
外部JSのインポートもできる@If Model.IsOn Then
@<text>
<script src="">http://d3js.org/d3.v3.js">
<script type="text/javascript">
// ・・・略・・・
</script>
</text>
End If
「@:」「@<text>」の文法の説明は以下を参照のこと http://blogs.yahoo.co.jp/dk521123/35586581.html
サンプル
モデル
* SampleJavaScriptModel.vbPublic Class SampleJavaScriptModel
Public Property IsOn As Boolean
End Class
コントローラ
* SampleJavaScriptController.vbImports System.Web.Mvc Public Class SampleJavaScriptController Inherits Controller ' GET: SampleJavaScript Function Index() As ActionResult Dim model = New SampleJavaScriptModel() model.IsOn = True Return View(model) End Function End Class
ビュー
[1] Index.vbhtml@ModelType WebAppli.SampleJavaScriptModel
@Code
ViewData("Title") = "Index"
End Code
<h2>Index</h2>
<div id="result"></div>
@If Model.IsOn Then
@:<script type="text/javascript">
@: document.getElementById("result").innerText = "Hello!";
@:</script>
Else
@:<script type="text/javascript">
@: document.getElementById("result").innerText = "Good morning!";
@:</script>
End If
<h2>Index</h2>
[2] Index.vbhtml @ModelType WebAppli.SampleJavaScriptModel
@Code
ViewData("Title") = "Index"
End Code
<h2>Index</h2>
<div id="result"></div>
@If Model.IsOn Then
@<text>
<script type="text/javascript">
document.getElementById("result").innerText = "Hello!";
</script>
</text>
Else
@<text>
<script type="text/javascript">
document.getElementById("result").innerText = "Good morning!";
</script>
</text>
End If
<h2>Index</h2>
出力結果
* model.IsOn = True の場合Index Hello! Index* model.IsOn = False の場合
Index Good morning! Index