コントローラアクションでIsLocalプロパティをブール値に設定したと仮定します。
public ActionResult Index()
{
ViewBag.IsLocal = true;
return View();
}
ビューでこれを行うことができます:
<script type="text/javascript">
@if(ViewBag.IsLocal)
{
<text>alert("yeah");</text>
}
</script>
また、ViewBag/ViewDataは使用しないでください。ビューモデルと強く型付けされたビューを使用します。
だからここに私が好むより良いアプローチがあります。ビューモデルをJavaScript変数にJSONシリアル化して、それを処理することができます。このような:
@model MyViewModel
<script type="text/javascript">
var model = @Html.Raw(Json.Encode(Model));
// at this stage model is a javascript variable containing
// your server side view model so you could manipulate it as you wish
if(model.IsLocal)
{
alert("hello " + model.FirstName);
}
</script>
明らかに、ビューモデル全体が必要ない場合は、そのサブセットのみをJSONシリアル化できます=>クライアントスクリプトで必要となる部分のみ。