简体   繁体   中英

Best way to remove hardcoded string in javascript with Asp.Net MVC

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?

  1. Step one , use T4MVC to automatically generate a structured set of .NET classes that describe your ASP.NET MVC's application structure

  2. 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> 
  3. 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.

  4. Step four , use your newly defined JavaScript constants throughout your JavaScript files.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM