Check ViewBag Value is present in javascript

2019-07-25 00:54发布

问题:

I am using razor template and following is the scenario

$(function(){
   //if (ViewBag.IsCallFunction){
      somefunction();
   //
  //do something else
});

If a viewBag variable is present, i.e. not null and if it is set to true, then I would like to call some javascript function. How do I do this?

回答1:

@{if(ViewBage.somevalue!=null && ViewBage.somevalue=="true")
  {
   <script type="text/javascript">
   somefunction();
   </script>
  }
}

but remember this will get called as rendered, as per OP, you can't call it, you can render it, so call it inside document.ready when document is loaded



回答2:

<script type="text/javascript">
$(function() {
    @if (ViewData.ContainsKey("IsCallFunction") && ViewBag.IsCallFunction) 
    {
        <text>somefunction();</text>
    }
});
</script>

But I would recommend you using a view model instead of ViewBag, because in this case your code could be simplified:

<script type="text/javascript">
$(function() {
    @if (Model.IsCallFunction) 
    {
        <text>somefunction();</text>
    }
});
</script>


回答3:

You don't call a JavaScript function from Razor code because Razor runs on the server and JavaScript runs on the client.

Instead, you can emit JavaScript code to the client that then runs once the browser loads the HTML code generated by Razor.

You could do something like

<script type="text/javascript">
@* The following line is Razor code, run on the Server *@
@if (ViewData.ContainsKey("IsCallFunction") && ViewBag.IsCallFunction) { 
@* The following lines will be emitted in the generated HTML if the above condition is true *@
$(function(){
      somefunction();
  //do something else
});

@} @* This is the closing brace for the Razor markup, executed on the Server *@
</script>