Relative URL in JQuery Post Call

Depending on where you actually have your JavaScript located (inside the View or a separate JS file), you have a couple of options.

Option 1 – Inside the View

Simply use the Html Helpers to generate the links for you

<script type="text/javascript">
   $(function(){
        $.ajax({
           type: "POST",
           url: "@Url.Action("UpdateCheckBox", "CeduleGlobale")"
        });
   });
</script>

Option 2 – Standalone JS File

We typically have a function per page that sets up that page’s handlers. So, we can do something like the following:

View

<script type="text/javascript">
    $(function(){
        SetOrderPage('@Url.Action("UpdateCheckBox", "CeduleGlobale")');
    });
</script>

Standalone JS File

function SetOrderPage(ajaxPostUrl){
       $.ajax({
           type: "POST",
           url: ajaxPostUrl
       )};
}

Option 3 – Standalone JS file Method 2

You could have a global variable in your in your JS file that is the siteroot. The draw back here is that you will need to hand create each of your action method paths. On each page, you could set the site root global variable as such:

Standalone JS File

var siteRoot;

View

<script type="text/javascript">
    siteRoot="@Request.ApplicationPath";
</script>

Keep in mind you cannot use Razor syntax in a stand alone JS file. I believe that it is best to let Razor/MVC/.NET dynamically give you the site path or URL route as it will really cut down on the mistakes that could be made when moving between sites/virtual directories.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)