title: $.AJAX .post() not working - Server responded with a status of 404 (Not Found)?
body: <p>I am working on a View for an MVC5 app. This is an <code>Edit</code> View with multiple properties, several of which are related to other models. I have my main <code>INV_Assets</code> model and then several other tables for <code>Location, Manufacturer, Model, Status, Type, Vendor</code>, etc. On this <code>Edit</code> view, I'm displaying those particular properties as dropdown lists containing all values currently in those tables, along with a [CREATE NEW] button by each list.</p>
  
  <p>When user selects the [CREATE NEW] button, I have a hidden form which appears and allows a user to enter a new value for the specific Table/DropDown. I've got everything working except the POST where I add the value to the Table and refresh the DropDown list.</p>
  
  <p>Below is what I have put together for my first dropdown (the <code>Model</code> selection) -- everything is functioning up to the POST:</p>
  
  <p><strong>INV_Assets.Edit View</strong>:</p>
  
  <pre><code>&lt;div class="form-group"&gt;
          &lt;span class="control-label col-md-2"&gt;Manufacturer:&lt;/span&gt;
          &lt;div class="col-md-4"&gt;
              @Html.DropDownListFor(model =&gt; model.Manufacturer_Id, (SelectList)ViewBag.Model_List, htmlAttributes: new { @class = "form-control dropdown" })
              @Html.ValidationMessageFor(model =&gt; model.Manufacturer_Id, "", new { @class = "text-danger" })
          &lt;/div&gt;
          &lt;div class="col-md-1"&gt;
              &lt;div class="btn-group"&gt;
                  &lt;button type="button" class="btn btn-success" aria-expanded="false"&gt;CREATE NEW&lt;/button&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  </code></pre>
  
  <p><strong>INV_Assets.Edit Script</strong>:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  
          $(document).ready(function () {
              // Show() form to enter new Model.
              $('#createNewModel').click(function () {
                  $('#createModelFormContainer').show();
              })
  
              // Submit new Model value and refresh dropdown
              $('#submitNewModel').click(function () {
                  alert("New Function!"); // WORKING
  
                  var form = $(this).closest('form');
                  var url = form.attr('action');
                  var data = { Text: form.find('input').first().val() };
  
                  alert("Prior to Post"); // WORKING
  
                  $.post(url, form.serialize(), function (data) {
  
                      alert("Begin POST!"); // NOT BEING REACHED!
  
                      $('#selectModel').append($('&lt;option&gt;&lt;/option&gt;').val(data.ID).text(data.Text));
                      form[0].reset();
                      $('#createModelFormContainer').hide();
                  })
              });
          });
  &lt;/script&gt;
  </code></pre>
  
  <p>When my code hits the <code>$.post</code> something goes wrong. It was previously getting: </p>
  
  <p><img src="https://i.stack.imgur.com/VCIfZ.jpg" alt="Script1"></p>
  
  <p>Since <code>post()</code> seemed to be the anonymous function, I assumed I did not have ajax installed. I then installed <code>Microsoft.jQuery.Unobtrusive.Ajax</code>, which now renders my error as: <code>Failed to load resource: the server responded with a status of 404 (Not Found) - http://localhost:4545/INV_Assets</code>.</p>
  
  <p>Any thoughts on this? </p>
  
  <p>As best as I understand it, my submit should be posting to my below  <code>createNewModel()</code> method inside my <code>INV_AssetsController</code>:</p>
  
  <pre><code>    [HttpPost]
      public JsonResult createNewModel(INV_Models model)
      {
          model.created_date = DateTime.Now;
          model.created_by = System.Environment.UserName;
          model.modified_date = DateTime.Now;
          model.modified_by = System.Environment.UserName;
  
          if (ModelState.IsValid == false &amp;&amp; model.Id == 0)
          {
              ModelState.Clear();
          }
  
          if (ModelState.IsValid)
          {
              db.INV_Models.Add(model);
              db.SaveChangesAsync();
          }
  
          return Json(new { ID = model.Id, Text = model.model_description });
      }
  </code></pre>
  
  <p>Assuming it is something to do with my routing, this is my current <code>RouteConfig.cs</code>:</p>
  
  <pre><code>public static void RegisterRoutes(RouteCollection routes)
      {
          routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  
          routes.MapRoute(
              name: "Default",
              url: "{controller}/{action}/{id}",
              defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
          );
      }
  </code></pre>
  
  <p>Anyone with more expertise able to see what I'm doing wrong?</p>
  
  <hr>
  
  <p><strong>EDIT</strong>:</p>
  
  <p>Using <strong>wahwahwah</strong>'s suggestion, I made the following modification to my script:</p>
  
  <pre><code>        $('#createNewModel').click(function () {
              $('#createModelFormContainer').show();
          })
  
          $('#submitNewModel').click(function () {
              var form = $(this).closest('form');
              var data = { Text: form.find('input').first().val() };
              $.ajax({
                  type: "POST",
                  dataType: "JSON",
                  url: '@Url.Action("createNewModel", "INV_Assets")',
                  data: data,
                  success: function (resp) {
                      alert("SUCCESS!");
                  },
                  error: function () {
                      alert("ERROR!");
                  }
              });
  </code></pre>
  
  <p>Going this route, my <code>createNewModel()</code> action is correctly called in the controller, but fails out at <code>db.SaveChangesAsync()</code>:</p>
  
  <pre><code>    [HttpPost]
      public JsonResult createNewModel(INV_Models model)
      {
          model.created_date = DateTime.Now;
          model.created_by = System.Environment.UserName;
          model.modified_date = DateTime.Now;
          model.modified_by = System.Environment.UserName;
  
          if (ModelState.IsValid == false &amp;&amp; model.Id == 0)
          {
              ModelState.Clear();
          }
  
          if (ModelState.IsValid)
          {
              db.INV_Models.Add(model);
              db.SaveChangesAsync();
          }
  
          return Json(new { ID = model.Id, Text = model.model_description });
      }
  </code></pre>
  
  <p>The error is as follows: </p>
  
  <pre><code>An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code
  
  Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
  </code></pre>
  
  <hr>
  
  <p><strong>EDIT2</strong>:</p>
  
  <p>Modified my troublesome code to be in a try/catch and then set a <code>Watch</code> on ex:</p>
  
  <pre><code>    [HttpPost]
      public JsonResult createNewModel(INV_Models model)
      {
  
              model.created_date = DateTime.Now;
              model.created_by = System.Environment.UserName;
              model.modified_date = DateTime.Now;
              model.modified_by = System.Environment.UserName;
  
              // Set ID
              int lastModelId = db.INV_Models.Max(mdl =&gt; mdl.Id);
              model.Id = lastModelId+1;
  
              if (ModelState.IsValid == false &amp;&amp; model.Id &gt; 0)
              {
                  ModelState.Clear();
              }
  
              if (ModelState.IsValid)
              {
                  try
                  {
                      db.INV_Models.Add(model);
                      db.SaveChangesAsync();}
                  catch (Exception ex)
                  {
                      Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                  }
              }
  
              return Json(new { ID = model.Id, Text = model.model_description });  
      }
  </code></pre>
  
  <p><code>ex</code> Details:</p>
  
  <p><img src="https://i.stack.imgur.com/c7YHT.jpg" alt="DbEntityValidationErrorDetails"></p>
  
  <p>Apparently the <code>description</code> I'm entering for the new Model is not being included in the new <code>Model</code> that is being saved?</p>
  
  <hr>
  
  <p><strong>EDIT3</strong>:</p>
  
  <p>Below is my current script/controller action code. When I break inside the controller and type <code>?model.model_description</code> into the <code>Immediate Window</code>, it returns <code>null</code>.</p>
  
  <p>Regarding my below alerts, the value in my <code>&lt;input type="text" name="model_description" /&gt;</code> appears to not be correctly stored in the variable for use by JSON, and thus is not passed to the controller?</p>
  
  <ul>
  <li><code>alert(test)</code>: <code>S2EFXrd3nXdWOIES5eBi4e_Fz3wrqCwP44hhQ7kj_foL3qkNv26OBgQoqHC-8BV8HKC6xdDEa7uCBnhOFPKL3AwIko99p-j_887qQgOXRPg1</code></li>
  <li><code>alert(data.model_description)</code>: <code>S2EFXrd3nXdWOIES5eBi4e_Fz3wrqCwP44hhQ7kj_foL3qkNv26OBgQoqHC-8BV8HKC6xdDEa7uCBnhOFPKL3AwIko99p-j_887qQgOXRPg1</code></li>
  <li><code>alert(jasonData.valueOf())</code>: <code>{"model_description":"S2EFXrd3nXdWOIES5eBi4e_Fz3wrqCwP44hhQ7kj_foL3qkNv26OBgQoqHC-8BV8HKC6xdDEa7uCBnhOFPKL3AwIko99p-j_887qQgOXRPg1"}</code></li>
  </ul>
  
  <p><strong>INPUT FORM</strong>:</p>
  
  <pre><code>            &lt;div id="createModelFormContainer" style="display:none"&gt;
                  &lt;form action="/createNewModel"&gt;
                      &lt;input type="text" name="model_description" /&gt;
                      &lt;input type="button" id="submitNewModel" value="Submit" /&gt;
                  &lt;/form&gt;
              &lt;/div&gt;
  </code></pre>
  
  <p><strong>Script</strong>:</p>
  
  <pre><code>        $('#submitNewModel').click(function () {
  
              var form = $(this).closest('form');
  
              var test = form.find('input').first().val();
              alert(test);
  
              var data = { model_description: form.find('input').first().val() };
              alert(data.model_description);
  
              //var data = { model_description: $("input[name = 'model_description']").text.toString() };
  
              var jsonData = JSON.stringify(data);
              alert(jsonData.valueOf());
  
              $.ajax({
                  type: "POST",
                  dataType: "JSON",
                  url: '@Url.Action("createNewModel", "INV_Assets")',
                  data: jsonData,
                  success: function (resp) {
                      alert("SUCCESS!");
                  },
                  error: function () {
                      alert("ERROR!");
                  }
              });
  </code></pre>