title: Ajax Jquery post using relative URL
body: <p>I have a create view and an edit view, almost identical. They both include a cascading dropdown list. The value of the second list is part of the data that's being created or edited. The first dropdown is just a filter for values in the second list.</p>
  
  <p>Both views use the same script which attaches a handler for the change event in the first dropdown list. The handler makes a post to a method in the controller.</p>
  
  <p>When I run the create view and change the first dropdown list it works fine. The second list is updated. When I try in the edit view I get a 500 Internal Server Error.</p>
  
  <p>I've had a look in Firebug. I put a break in the handler. It gets called in both cases when selecting. The data that gets sent appears to be the same ( $(this).serialize() looks the same ).<br>
  The Firebug console says:
  The required anti-forgery form field &quot;__RequestVerificationToken&quot; is not present.
  I don't see that I'm requiring one to call this method, but there are of course other methods (actions) that do require one.</p>
  
  <p>I've never used Firebug before yesterday though, so there's possibly a lot more that could be checked if one knew how. (I am completely new to MVC and web applications in general.)</p>
  
  <p>I also have a break in my controller method. It gets hit when called from the create view only.</p>
  
  <p>In a fit of desperation I tried changing the call type to GET instead of POST. That resulted in a controller method with a different name being called (the HttpGet EDIT), which I find disturbing to say the least.</p>
  
  <p>I get the feeling that the method I'm calling isn't found (in edit). Instead an attempt is made with some other method (I don't know which one) and that method requires an antiforgery token.</p>
  
  <p><strong>EDIT :</strong>
  A nip of fresh air and I realize that of course I know which action gets called: It's the HttpPost Edit action (which requires an antiforgery token). This is of course the normal form submit action. A quick run in the debugger confirms this. The fact that this call fails for the reason at hand is clear. But why does this action get called at all?</p>
  
  <p><strong>UPDATE :</strong>
  The Firebug console indicates that different actions are being called. In the Create case it's .../_an_alphanumeric_literal_/Order/PopulateAvtalDDL, which is what I want. In the Edit case it's .../_an_alphanumeric_literal_/Order/<strong>Edit</strong>/PopulateAvtalDDL. Is this a routing problem? If so, I still don't get it. Both calls are made from the same script and I only have one route set up (basically the default route for MVC 4):</p>
  
  <pre><code>routes.MapRoute(
              name: "Default",
              url: "_an_alphanumeric_literal_/{controller}/{action}/{id}",
              defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
          );
  </code></pre>
  
  <p><strong>UPDATE :</strong>
  I finally found some related information: <a href="https://stackoverflow.com/questions/4765740/relative-urls-in-ajax-requests?rq=1">Relative URLs in AJAX requests</a>.
  It is a routing problem then. If I change my script URL from  the relative <code>PopulateAvtalDDL</code> to the absolute <code>/_an_alphanumeric_literal_/Order/PopulateAvtalDDL</code> it works from both views. The answer in the quoted link states that a path is relative to the current URL in the browser. In my case that is <code>http://localhost:51852/_an_alphanumeric_literal_/Order/Edit/6?markedOrderId=0</code> and <code>http://localhost:51852/_an_alphanumeric_literal_/Order/Create?markedOrderId=0</code>. When the relative URL is constructed the last segment is replaced. In the Create case that is <strong>Create</strong>, but in the Edit case it is <strong>6</strong> (ID of edited data). I understand what's happening!</p>
  
  <p>My solution then:  </p>
  
  <p>Add a div around the filter DDL (in both views) setting the URL: <code>&lt;div id="kundDDL" data-url="@Url.Action("PopulateAvtalDDL", "Order")"&gt;</code>. Then in the script access that URL <code>url: $('#kundDDL').data('url')</code>.</p>
  
  <p>Here's the code for the create view:</p>
  
  <pre><code>@model AssetMgmt.Models.OrderEditVM
  @using AssetMgmt.Models;
  
  @{
      ViewBag.Title = MsgString.LblCreateNew + " order";
  }
  
  &lt;h2&gt;@ViewBag.Title&lt;/h2&gt;
  
  
  @using (Html.BeginForm(null, null, FormMethod.Post))
  {
      @Html.ValidationSummary(true)
      @Html.AntiForgeryToken()
  
      @Html.HiddenFor(m =&gt; m.MarkedOrderId)
  
      &lt;fieldset&gt;
          &lt;legend&gt;Filter&lt;/legend&gt;
  
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(m =&gt; m.KundId)
          &lt;/div&gt;
          &lt;div class="dropdownlist"&gt;
              @Html.DropDownListFor(m =&gt; m.KundId, Model.KundDropDown, string.Empty)
          &lt;/div&gt;
          &lt;div class="dropdown-validation-error"&gt;
              @Html.ValidationMessageFor(model =&gt; model.KundId)
          &lt;/div&gt;
      &lt;/fieldset&gt;
  
      &lt;fieldset&gt;
          &lt;legend&gt;Orderdata&lt;/legend&gt;
  
          &lt;div id="avtalDDL"&gt;
              @Html.Partial("_AvtalDDL")
          &lt;/div&gt;
  
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(model =&gt; model.Ordernummer)
          &lt;/div&gt;
          &lt;div class="editor-field"&gt;
              @Html.EditorFor(model =&gt; model.Ordernummer)
              @Html.ValidationMessageFor(model =&gt; model.Ordernummer)
          &lt;/div&gt;
  
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(model =&gt; model.Beställare)
          &lt;/div&gt;
          &lt;div class="editor-field"&gt;
              @Html.EditorFor(model =&gt; model.Beställare)
              @Html.ValidationMessageFor(model =&gt; model.Beställare)
          &lt;/div&gt;
  
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(model =&gt; model.Orderdatum)
          &lt;/div&gt;
          &lt;div class="editor-field"&gt;
              @Html.EditorFor(model =&gt; model.Orderdatum)
              @Html.ValidationMessageFor(model =&gt; model.Orderdatum)
          &lt;/div&gt;
  
          &lt;p&gt;
              &lt;input type="submit" value="@MsgString.LblSave" /&gt;
          &lt;/p&gt;
      &lt;/fieldset&gt;
  }
  &lt;div&gt;
      @Html.ActionLink(MsgString.LblBack, "Index", new { markedOrderId = Model.MarkedOrderId })
  &lt;/div&gt;
  
  @section Scripts {
      @Scripts.Render("~/bundles/jqueryval")
      &lt;script type="text/javascript" src="~/Scripts/jquery.maskedinput-1.3.1.min.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="~/Scripts/assetMgmtMasks.js"&gt;&lt;/script&gt;
      &lt;script src="~/Scripts/assetMgmtOrderPopulateDDL.js" type="text/javascript"&gt;&lt;/script&gt;
  }
  </code></pre>
  
  <p>Here's the Edit view:</p>
  
  <pre><code>@model AssetMgmt.Models.OrderEditVM
  @using AssetMgmt.Models;
  
  @{
      ViewBag.Title = MsgString.LblEdit + " order";
  }
  
  &lt;h2&gt;@ViewBag.Title&lt;/h2&gt;
  
  @using (Html.BeginForm(null, null, FormMethod.Post))
  {
      @Html.ValidationSummary(true)
      @Html.AntiForgeryToken()
  
      @Html.HiddenFor(model =&gt; model.OrderId)
      @Html.HiddenFor(model =&gt; model.Timestamp)
      @Html.HiddenFor(model =&gt; model.MarkedOrderId)
  
      &lt;fieldset&gt;
          &lt;legend&gt;Filter&lt;/legend&gt;
  
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(m =&gt; m.KundId)
          &lt;/div&gt;
          &lt;div class="dropdownlist"&gt;
              @Html.DropDownListFor(m =&gt; m.KundId, Model.KundDropDown, string.Empty)
          &lt;/div&gt;
          &lt;div class="dropdown-validation-error"&gt;
              @Html.ValidationMessageFor(model =&gt; model.KundId)
          &lt;/div&gt;
      &lt;/fieldset&gt;
  
      &lt;fieldset&gt;
          &lt;legend&gt;Orderdata&lt;/legend&gt;
  
          &lt;div id="avtalDDL"&gt;
              @Html.Partial("_AvtalDDL")
          &lt;/div&gt;
  
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(model =&gt; model.Ordernummer)
          &lt;/div&gt;
          &lt;div class="editor-field"&gt;
              @Html.EditorFor(model =&gt; model.Ordernummer)
              @Html.ValidationMessageFor(model =&gt; model.Ordernummer)
          &lt;/div&gt;
  
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(model =&gt; model.Beställare)
          &lt;/div&gt;
          &lt;div class="editor-field"&gt;
              @Html.EditorFor(model =&gt; model.Beställare)
              @Html.ValidationMessageFor(model =&gt; model.Beställare)
          &lt;/div&gt;
  
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(model =&gt; model.Orderdatum)
          &lt;/div&gt;
          &lt;div class="editor-field"&gt;
              @Html.EditorFor(model =&gt; model.Orderdatum)
              @Html.ValidationMessageFor(model =&gt; model.Orderdatum)
          &lt;/div&gt;
  
          &lt;p&gt;
              &lt;input type="submit" value="@MsgString.LblSave" /&gt;
          &lt;/p&gt;
      &lt;/fieldset&gt;
  }
  
  &lt;div&gt;
      @Html.ActionLink(MsgString.LblBack, "Index", new { markedOrderId = Model.MarkedOrderId })
  &lt;/div&gt;
  
  @section Scripts {
      @Scripts.Render("~/bundles/jqueryval")
      &lt;script type="text/javascript" src="~/Scripts/jquery.maskedinput-1.3.1.min.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="~/Scripts/assetMgmtMasks.js"&gt;&lt;/script&gt;
      &lt;script src="~/Scripts/assetMgmtOrderPopulateDDL.js" type="text/javascript"&gt;&lt;/script&gt;
  }
  </code></pre>
  
  <p>The script:</p>
  
  <pre><code>$(document).ready(function () {
      //Kund select
      $('#KundId').change(function () {
          $.ajax({
              url: 'PopulateAvtalDDL',
              type: 'post',
              data: $(this).serialize(),
              success: function (result) {
                  $('#avtalDDL').html(result);
              },
              error: function (xhr, ajaxOptions, thrownError) {
                  alert(xhr.status);
                  alert(xhr.statusText);
                  alert(thrownError);
              }
          });
          return false;
      });
  });
  </code></pre>
  
  <p>The signature of the controller method:</p>
  
  <pre><code>[HttpPost]
  public PartialViewResult PopulateAvtalDDL(int kundId = 0)
  </code></pre>