Possible to Access MVC Viewbag Object from JavaScript File

Possible to access MVC ViewBag object from Javascript file?

I don't believe there's currently any way to do this. The Razor engine does not parse Javascript files, only Razor views. However, you can accomplish what you want by setting the variables inside your Razor view:

<script>
var someStringValue = '@(ViewBag.someStringValue)';
var someNumericValue = @(ViewBag.someNumericValue);
</script>
<!-- "someStringValue" and "someNumericValue" will be available in script -->
<script src="js/myscript.js"></script>

As Joe points out in the comments, the string value above will break if there's a single quote in it. If you want to make this completely iron-clad, you'll have to replace all single quotes with escaped single quotes. The problem there is that all of the sudden slashes become an issue. For example, if your string is "foo \' bar", and you replace the single quote, what will come out is "foo \\' bar", and you're right back to the same problem. (This is the age old difficulty of chained encoding.) The best way to handle this is to treat backslashes and quotes as special and make sure they're all escaped:

  @{
var safeStringValue = ViewBag.someStringValue
.Replace("\\", "\\\\")
.Replace("'", "\\'");
}
var someStringValue = '@(safeStringValue)';

How do I access ViewBag from JS

if you are using razor engine template then do the following

in your view write :

<script> var myJsVariable = '@ViewBag.MyVariable' </script>

UPDATE:
A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```

<head>
<script>
var AppConfig = @Html.Raw(Json.Encode(new {
baseUrl: Url.Content("~"),
fbApi: "get it from db",
awsUrl: "get it from db"
}));
</script>
</head>

And you can use it in your JavaScript code as follow:

<script>
myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
alert(myProduct.fullUrl);
</script>

Access ViewBag in JS file - Asp.net MVC

You can't. You can write ViewBag value in hidden input and then read it from js file:

<input type="hidden" value="@ViewBag.Mode" id="mode" />

JS file:

var mode = document.getElementById('mode').value;

EDIT: Another option:

<script src="..." type="text/javascript" onload="InitMyScript('@ViewBag.Mode')"></script>

JS file:

function InitMyScript(mode){
//other code here
}

Access ViewBag from JavaScript

Razor code can be added with Javascript
var x=JSON.Parse(@ViewBag.objJson...)

viewbag object pass to javascript

What is the type returned by getFilledReportWithEntitiesById()?

Presumably, it's a Application.Database.ACCIDENT. All the view engine does is invoke .ToString() on what it's given. And the default implementation for .ToString() on any reference type (any child of object basically) is to return the type name.

If you want a custom string representation of your type, then that type needs to override .ToString(). For example:

public override string ToString()
{
return string.Format("{0} - {1}", ID, Name);
}

If the object has an ID property and a Name property then its string representation would then be those values separated by a hyphen (with spaces in between). However you want to structure the string representation of your object would be done within this method.

Conversely, if you don't want it to be a string, but want the JavaScript code to use it as an object, then you want to serialize it to JSON. Something like this:

var data = @Json.Encode(ViewBag.Report);

(You might need to tweak that a little bit, I don't have an environment handy to test it. But you get the idea... To use it as an object in JavaScript code it needs to be serialized to a JavaScript object literal.)



Related Topics



Leave a reply



Submit