简体   繁体   中英

pass C# parameters to JS

I have a C#-MVC project. I want to refresh the page every X second - I put in the cshtml file the code:

<script type="text/JavaScript">
   timedRefresh(X);
</script>

but I need to take X from C#, let's say it's "ViewBag.Seconds". How can I do this?

Razor doesn't care if it's outputting HTML or javascript, so you could do:

<script type="text/JavaScript">
   timedRefresh(@(ViewBag.Seconds));
</script>

If you are using the Razor syntax it can be done like this:

<script type="text/JavaScript">
  timedRefresh(@(ViewBag.Seconds));
</script>

The IntelliSense may report an error or warning, but it works anyway.

It's pretty easy

<script type="text/JavaScript">
   timedRefresh(@ViewBag.Seconds);
</script>

You can use an Action too. like this:

<script type="text/JavaScript">
   timedRefresh(@(Html.Action("Action","Controller")));
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM