Sunday, February 1, 2015

.NET MVC: Refactoring-friendly JavaScript

The Problem

It often happens that you need to make an Ajax call from you JavaScript to an MVC action. So you code it like this (I'm assuming that your JavaScript is in a separate file):

$.ajax({
    url: "MyWebApp/Data/GetAllProducts",
    type: "POST",
    dataType: "json",
    headers: { ... },
    data: { ... },
    success: function (data) { ... }
    error: function (result, error, moreInfo) { ... }
});

Later you decide the GetAllProducts action should really be called GetProducts, because you want to use the same action to get a list of all products, and a list of filtered products, depending on parameters.

So you refactor-rename the action using vanilla Visual Studio, or ReSharper, or another favorite plugin. But guess what? Now you have to go and manually change all your hard-coded JavaScript strings to point to the right action. It's possible that the tool will offer to change these strings too, but you never know whether it'll find all of them or not.

The Solution

In the Razor view of the relevant page, you can initialize your JavaScript like this:

$(document).ready(function() {
    MyScript.init({
        getProductsUrl: "@(Url.Action("GetAllProducts", "Data"))"
    });
});

Define your init function in the JavaScript:

var MyScript = new function() {
    var m_options;

    this.init = function(options) {
        m_options = options;
    };
}

Later you can make your Ajax call like this:

$.ajax({
    url: m_options.getProductsUrl,
    type: "POST",
    dataType: "json",
    headers: { ... },
    data: { ... },
    success: function (data) { ... }
    error: function (result, error, moreInfo) { ... }
});

Voila! Now when you refactor-rename the tool won't be confused and you just saved yourself half an hour of work. And, you can use the same technique to pass in other things from Razor. Just add properties to your options object.
And here is a link to the snippet in the solution at INT64:

http://www.int64.io/Home/Snippet/SWh2V1pxU0JEeG9sNE8wanJjVDljUT090

8 comments:

  1. Or, you could use RequireJS.NET and keep your JS, HTML and C# separate.

    ReplyDelete
    Replies
    1. This is also a possibility, but a heavier option. It may be a good choice for more complex situations.

      Delete
  2. Helpful article! I have a doubt,I need to make a ajax call (to say the URL is 'Customer/GetAllProducts') . Now if I deploy the application in a folder C:\MyApplication, I am required to prepend MyApplication to the URL making it,'MyApplication/Customer/GetAllProducts',else the Ajax call is not working. Every time I change the environment I need to make this change. Do you know any crisp process for it?

    ReplyDelete
    Replies
    1. You can still use the @Url.Action extension method. Take a look at this StackOverflow question: http://stackoverflow.com/questions/434604/how-to-i-find-the-absolute-url-of-an-action-in-asp-net-mvc

      Delete
  3. TechnoSoftwar dedicated and experienced team of Dot Net developers works on various projects and deliver outstanding results to their clients.
    TechnoSoftwar basically deals in web design and development, Mobile application development and Digital Marketing simultaneously works on Asp.net framework and MVC also.

    ReplyDelete
  4. Thank you for such an interesting article. I am glad that you have given us very valuable tips to solve this problem.

    ReplyDelete
  5. it is really a problem! I encountered such a course not! but take note

    ReplyDelete
  6. Needless to say, we're glad we hedged our bets on this one. We've additionally added a pair of photographs from readers showing different purported roulette anomaly occurrences at the bottom of the original submit. 바카라사이트 But Arizona tribes agreed to help off-reservation sports activities betting, which should kick off in September, in exchange for new spanking new|for model new} desk video games and sportsbooks of their very own. Gifted with a superb thoughts that might retain numbers and statistics, he went to study medication — a noble pursuit that happy his father. Traditional knowledge dictates that you should to} in all probability discuss to one of many Bunny Girls who give imprecise hints on the likelihood of a jackpot happening. However, from what we will to} tell, this doesn't truly do anything.

    ReplyDelete