简体   繁体   中英

ASP.NET MVC error to use $.post(), this method put another controller name to the call

I have an ASP.NET MVC application. I have a problem when I use $.pos() . This method receives in the first parameter the controller name and action name, for example "Controller/Action" . The problem is that in some place for no reason the post method adds the controller name to the post method. I can observe this using firebug . Here's an example from my source code:

$.post("Customer/Create", {}, function (data) {
    $("#Detalle").html("");
    $("#Detalle").append(data);
});

For no reason the call contains "Customer/Customer/Create" . I can observe it in firebug and this causes an error because "Customer/Customer/Create" doesn't exist. What is the problem? I have seen that if I use $.ajax or ().load I don't have this problem, but I prefer to use $.post instead of $.ajax because will cause a great change. Can someone explain to me what is cuasing the problem? Thank you friends.

Instead of this:

$.post("Customer/Create", {}, function (data) { $("#Detalle").html(""); $("#Detalle").append(data); });

Try this, add a slash beginning of your url :

$.post("/Customer/Create", {}, function (data) { $("#Detalle").html(""); $("#Detalle").append(data); });

To avoid the slash related error or correct path best way use Url like below:

  $.post('@Url.Action("Create","Customer")', {}, function (data) {
            $("#Detalle").html("");
          $("#Detalle").append(data);
  });

or if are using expernal js file than best way to manage url .Create global variables in Layout or View like below:

  <Script>
    var customerUrl = {
    Create: '@Url.Action("Create","Customer")'
    //Append mor url accoring to your requirement.
   }
 </script>

and then in you external js file use following :

  $.post(customerUrl.Create , {}, function (data) {
            $("#Detalle").html("");
          $("#Detalle").append(data);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM