0

From this thread Passing dynamic javascript values using Url.action(), how can something like that be put into a javascript file? This would be the AngularJS controller file.

From the example above, the following can be used in an AngularJS controller defined in the _Layout.cshtml script tags:

var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;

The issue is that the asp.net MVC code doesn't play well when put into a javascript file. It works fine when in the _Layout.cshtml script tags. But not in a JS file.

Community
  • 1
  • 1
4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • Since ASP.Net MVC cannot not pre process, JS file, i think this is not possible. Check this SO post http://stackoverflow.com/questions/10389649/possible-to-access-mvc-viewbag-object-from-javascript-file – Chandermani Nov 30 '14 at 06:30

1 Answers1

0

For scenarios like these, I do something like the following

Say in my Angular controller I need to pass a value of the LoggedInUser, for which I have a server side Helper class available.

So in my Razor view I do something like this

<script type="text/javascript">
window.loggedInUser = '@MyHelper.LoggedInUser()';
</script>

And then access this global variable in my Angular controller.

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • Ok. I guess that doesn't really help since the majority of my code will still be in the _Layout.cshtml and not in any JS file. It would be best to keep all JS that works with Razor in the _Layout.cshtml rather than trying to force it into a JS file. Would you agree? – 4thSpace Nov 30 '14 at 15:31
  • No. I would go for JS to be in seperate JS files. – Yasser Shaikh Dec 01 '14 at 05:43