user1765862 user1765862 - 5 months ago 105
Javascript Question

ViewData is not defined

inside controller I'm checking state of some property and based on that I want to send on the view some flag. I decide to use ViewData for data.

if (model.MyProp == null)
{
ViewData["MyFlag"] = "yes"; // it doesn't need to be yes, basically if exist
}


and inside razor view in embeded js script code

<script>
if (ViewData["MyFlag"] != undefined) {
alert('0');
}
</script>


on page render firebug console report me error


ReferenceError: ViewData is not defined


so what I'm doing wrong here?

Answer

You should use razor syntax(@) to access ViewData inside javascript.

<script>
  if (@ViewData["MyFlag"] != undefined) {
    alert('0');
  }
</script>