-2

I pass some data (reference type or value type) in action function using ViewBag or ViewData.

The passed data (in ViewData or ViewBag) I assigned it to JavaScript variable on client side:

var stuff = @ViewBag.somedata;

My question is what the type of the variable stuff it will be? Is it JavaScript object? or string? or maybe string in JSON format?

halfer
  • 19,824
  • 17
  • 99
  • 186
Michael
  • 13,950
  • 57
  • 145
  • 288
  • 1
    possible duplicate of [How do I write unencoded Json to my View using Razor?](http://stackoverflow.com/questions/4072762/how-do-i-write-unencoded-json-to-my-view-using-razor) – Daniel J.G. Apr 29 '15 at 14:33

2 Answers2

1

It will be string. You may have to use eval if you want convert that into javascript recognizable.

Kumar
  • 21
  • 3
1

what the type of the variable stuff it will be?

Javascript has types now? Yes it does, but I don't think that is the question you want answered. Furthermore your question lacks lots of detail about what exactly you want to do. Where does the data come from? What do you want to do with it? Why do you want to assign it to a Javascript variable?

Anyway, this:

var stuff = @ViewBag.somedata;

Will only work if @ViewBag.somedata contains a number (depending on culture though) or object whose .ToString() representation is valid Javascript.

Razor has no notion of Javascript. Values you print will be html-encoded. If ViewBag.somedata contains a number, your HTML will go look like this:

var stuff = 42;

When it's a decimal and your culture uses comma for that:

var stuff = 4,2;

If it contains a string, it'll look like this:

var stuff = Hello, world!;

And if it by some magic contains a valid Javascript object initializer:

var stuff = { foo: bar };

But usually, it'll just print the type name for a reference type:

var stuff = System.Collections.Generic.List`1[string];

Almost all examples above won't work. So you'll want to use quotes:

var stuff = '@ViewBag.somedata';

But then still your data will be HTML-encoded, so if you want to convert a C# reference type to JSON and assign that to a Javascript variable, do as explained in How do I write unencoded Json to my View using Razor?:

var stuff = @Html.Raw(Json.Encode(Model.PotentialAttendees));
Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • thanks for this good explanation!But what if ViewBag.somedata contains json string format?Do I have to use json encode anyway? – Michael Apr 30 '15 at 06:11