Question

I want to display the data from a ViewBag in my View with Javascript. Here is my code.

View

<span id='test'></span>

Javascript

function myFunction()
{
    $('#test').text('@ViewBag.Test');
}

When myFunction() is called I get the text @ViewBag.Test but not his value. How can I fix this ?

Was it helpful?

Solution

You need to place your JavaScript which takes the @ViewBag.Test value in a page which is interpreted by the Razor view engine. My guess is that this is currently not the case.

If you want to keep your javascript codebase separate from the view (which is entirely reasonable) you can use a global variable:

// in the view:
var testText = '@ViewBag.Test';

// in external js
function myFunction() {
    $('#test').text(window.testText);
}

Alternatively, you can use a data-* attribute:

<span id='test' data-text="@ViewBag.Test"></span>

// in external js
function myFunction() {
    $('#test').text(function() {
        return $(this).data('text');
    });
}

OTHER TIPS

What you should be ideally doing is passing the data to the view with a view model. Have a property to store that value you want to pass. For example. Let's think about a page to show the customer details and you want to get the last name in your javascript variable.

Your GET action method

public ActionResult View(int id)
{
  var vm=new CustomerViewModel(); 
  vm.LastName="Scott"; // You may read this from any where(DAL/Session etc)
  return View(vm);
}

and in your view which is strongly typed to your view model.

@model CustomerViewModel
<div>    
   Some Html content goes here
</div>
<script type="text/javascript">      
   var lastName="@Model.LastName";
   //Now you can use lastName variable
</script>

EDIT : (As per the question edit) To show the content on some event (ex : some button click), Store the value somewhere initially and then read it as needed and set it wherever you want.

@model CustomerViewModel
<div>    
    <span id="content"></span>
    @Html.HiddenFor(s=>s.LastName)
    <input type="button" id="btnShow" value="Show content" />
</div>
<script type="text/javascript">  
   $(function(){

      $("btnShow").click(function(e){
         $("#content").html($("#LastName").val());
      });

   }); 

</script>

Firstly make sure your ViewBag.Test does got a value, then use a div tag instead of a span and add the following code:

<script type="text/javascript">
    $(document).ready(function () {
        StartRead();
    });

    function StartRead() {
        document.getElementById("test").innerHTML = '@ViewBag.Test';
    }
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top