When deploying MVC app on server ajax cant find ac

2020-04-30 17:55发布

问题:

I have a MVC5 application. When I run it on my localhost everything works without any errors.

When I publish my app then I transfer it to Windows Server 2016, I put the files in wwwroot in the IIS folder and I link everything to create a new website in IIS. I then run the website and it works. I get my javascript code to work, but when I go and run my ‘ajax’ methods I get an 404 error and in the function I cannot find my controller action so the method will work.

Here is my actual error:

xxx.xxx.xx x.219/Parts/DoPartBookFunc?bookval=8 404 (Not Found), Failed to load resource: the server responded with a status of 404 (Not Found)

I been researching and trying a bunch of different things, but so far no luck. Some things I tried were

  • @Url.action(“”,””)
  • adding a ~ in front
  • adding ../ in front
  • making a global file

and many other things. If someone knows how to fix this it would be hugely appreciated.

$("#PartBook").on("change", function () {
                var selectV = $(this).val();
                var selectT = $(this).text();         
        $.ajax({
                url: '/Parts/DoPartBookFunc',
                type: 'GET',
                dataType: 'json',
                data: { bookval: selectV },
                //contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    //alert("s" + data.PartNextNumber);

Here is my Solution everybody!

Changed my ajax() url to:

url: "@Url.Action("DoPartBookFunc", "Parts")",

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            /* Newly Added */ 
            routes.MapRoute(
                name: "AddNewControllerName",
                url: "AddNewControllerName/{action}/{id}",
                defaults: new { controller = "AddNewControllerName", action = "Index", id = UrlParameter.Optional }
                );

            /* Old Route */
            routes.MapRoute(
                name: "mass",
                url: "{action}/{id}",
                defaults: new { controller = "Parts", action = "Index", id = UrlParameter.Optional }
            ); 

回答1:

Try removing / from the url:

$("#PartBook").on("change", function () {
                var selectV = $(this).val();
                var selectT = $(this).text();         
        $.ajax({
                url: 'Parts/DoPartBookFunc',
                type: 'GET',
                dataType: 'json',
                data: { bookval: selectV },
                //contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    //alert("s" + data.PartNextNumber);
                    ...
                    })

or try adding this:

var RootUrl = '@Url.Content("~/")';

$.ajax({
type: "POST",
    url: RootUrl + "Parts/DoPartBookFunc",