How to display value of a ViewBag in my view with a JS function?

无人久伴 提交于 2019-12-08 07:00:39

问题


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 ?


回答1:


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');
    });
}



回答2:


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>



回答3:


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>


来源:https://stackoverflow.com/questions/19955823/how-to-display-value-of-a-viewbag-in-my-view-with-a-js-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!