Reputation: 12341
In my javascript files, I have too much hardcorded url that references controllers actions. Sometime, I also have messages displayed directly from my javascript.
What is the best way to remove all these hardcoded strings from javascript files?
Upvotes: 1
Views: 1404
Reputation: 2929
If you want to avoid using T4MVC, you could make a Controller that parses JS files. Just configure a route in Global.asax that catches all the javascript urls, and that action will ready the JS file, parse it, return a result with the URLs.
routes.MapRoute(
"Javascript",
"{url}.js",
new { controller = "Javascript", action = "Parse" }
);
Then write an action that reads the requested URL, finds the JS file, replaces values based on a Key/Value dictionnary. Perhaps even externalize that Key/Value dictionnary if could need that. The rest is up to you.
Another option would be to use a controller action that returns Javascript code. That javascript code would be a list of variables filled with URLs that are MVC generated.
Upvotes: 1
Reputation: 18012
Step one, use T4MVC to automatically generate a structured set of .NET classes that describe your ASP.NET MVC's application structure
Step two, create a new partial view that defines server-side information described by T4MVC as a set of Javascript constants.
<script type="text/javascript">
var SHOPPING_CART_DETAIL_URL = '@Url.Action(MVC.ShoppingCart.Detail(Model.ShoppingCartId))';
var CLIENT_DETAIL_URL = '@Url.Action(MVC.Client.Detail(Model.ClientId))';
var USER_IS_ADMIN = @(User.IsInRole(Roles.Admin) ? "true" : "false");
</script>
Step three, include this partial view in the head of whatever page you need it. You could also include it in the head of your general page layout. Make sure this loads before the rest of your JavaScript files.
Step four, use your newly defined JavaScript constants throughout your JavaScript files.
Upvotes: 3
Reputation: 29314
For that purpose I use T4MVC. It will allow you to use strongly typed objects in place of literal strings. You will need to initialize your javascript in your views, but other than that it works great.
For messages etc. here are some ideas: what are the different approaches to multilingual javascript applications
Upvotes: 1