Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 282373
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T05:17:00+00:00 2026-05-12T05:17:00+00:00

When doing a Ajax call to an MVC action currently I have my javascript

  • 0

When doing a Ajax call to an MVC action currently I have my javascript inside the View, not inside its own JS file.

It is then very easy to do this:

var xhr = $.ajax({
     url: '<%= Url.Action("DisplayItem","Home") %>/' + el1.siblings("input:hidden").val(),
     data: { ajax: "Y" },
     cache: false,
     success: function(response) { displayMore(response, el1, xhr) }
});

…then including the URL in the ajax call using Url.Action() inside the JS is pretty easy. How could i move this do its own JS file when without hard coding the URL?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T05:17:00+00:00Added an answer on May 12, 2026 at 5:17 am

    This way fully uses MVC Routing so you can fully take advantage of the MVC framework.
    Inspired by stusmith’s answer.

    Here I have an action in ApplicationController for dynamic javascript for this URL :

     /application/js
    

    I’m including static files here because I want just one master javascript file to download. You can choose to just return the dynamic stuff if you want:

         /// <summary>
        /// Renders out javascript
        /// </summary>
        /// <returns></returns>
        [OutputCache(CacheProfile = "Script")]
        [ActionName("js")]
        public ContentResult RenderJavascript()
        {
            StringBuilder js = new StringBuilder();
    
            // load all my static javascript files                    
            js.AppendLine(IO.File.ReadAllText(Request.MapPath("~/Scripts/rr/cart.js")));
            js.AppendLine(";");
    
            // dynamic javascript for lookup tables
            js.AppendLine(GetLookupTables());
            js.AppendLine(";");
    
            return new ContentResult()
            {
                Content = js.ToString(),
                ContentType = "application/x-javascript"
            };
        }
    

    This is the helper function that creates our lookup table. Just add in a line for each RouteUrl you want to use.

        [NonAction]
        private string GetLookupTables() 
        {
            StringBuilder js = new StringBuilder();
    
            // list of keys that correspond to route URLS
            var urls = new[] {
                new { key = "updateCart", url = Url.RouteUrl("cart-route", new { action = "updatecart" }) },
                new { key = "removeItem", url = Url.RouteUrl("cart-route", new { action = "removeitem" }) }
            };
    
            // lookup table function
            js.AppendLine("// URL Lookuptable");
            js.AppendLine("$.url=function(url) {");
            js.AppendLine("var lookupTable = " + new JavaScriptSerializer().Serialize(urls.ToDictionary(x=>x.key, x=>x.url)) + ";");
            js.AppendLine("return lookupTable[url];");
            js.AppendLine("}");
    
            return js.ToString();
        }
    

    This generates the following dynamic javascript, which is basically just a lookup table from an arbitrary key to the URL I need for my action method :

    // URL Lookuptable
    $.url=function(url) {
    var lookupTable = {"updateCart":"/rrmvc/store/cart/updatecart","removeItem":"/rrmvc/store/cart/removeitem"};
    return lookupTable[url];
    }
    

    In cart.js I can have a function like this.
    Note that the url parameter is taken from the lookup table :

     var RRStore = {};
     RRStore.updateCart = function(sku, qty) {
    
        $.ajax({
    
            type: "POST",
            url: $.url("updateCart"),
            data: "sku=" + sku + "&qty=" + qty,
            dataType: "json"
    
            // beforeSend: function (){},
            // success: function (){},
            // error: function (){},
            // complete: function (){},
        });
    
        return false;
    

    };

    I can call it from anywhere with just :

     RRStore.updateCart(1001, 5);
    

    This seemed to be the only way I could come up with that would allow me to use routing in a clean way. Dynamically creating URLS in javascript is icky and hard to test. Testing types can add in a layer somewhere in here to easily facilitate testing.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

On the client, I am doing a standard ajax call to an MVC action.
i am doing an ajax call and i refresh a partial view. Inside the
I am doing Ajax Call from View, then controller is fetching data from DB
Not sure what I'm doing wrong but I can't get my JQuery AJAX call
I have many places in my code doing $.ajax call can I define one
I am doing an AJAX call to a controller method on my ASP.Net MVC
I am doing a Ajax call with jquery and putting the content inside a
I have a view in which I am attempting to do an ajax call
I am doing an Ajax call which pulls some HTML in to a Div.
I am doing an AJAX call that returns some HTML and jQuery: <div id='selected'>Here

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.