如何使用ViewBag [复制]下MVC3剃刀将值分配给JavaScript变量(How to as

2019-07-31 00:26发布

可能重复:
如何分配下MVC3 JavaScript值

我尽量做到以下几点

<script type="text/javascript">

var techIDs = "";

@if (ViewBag.URLParameters != null)
{
   techIDs = '@ViewBag.URLParameters';
}

</script>

但现在看来,这是一种错误的做法。

任何线索如何可以做到?

谢谢!

Answer 1:

试试这个

var techIDs = "";
@if (ViewBag.URLParameters != null)
{
   @:techIDs = '@ViewBag.URLParameters';
}


Answer 2:

也许:

<script>
    var techIDs = '@Html.Raw(ViewBag.URLParameters ?? String.Empty)';
</script>


Answer 3:

我发现另一种方法

 var techIDs = "";

   @if (ViewBag.URLParameters != null)
   {
         <text>techIDs = '@ViewBag.URLParameters' ;</text>
   }


文章来源: How to assign value to JavaScript variable under MVC3 Razor with ViewBag [duplicate]