hkyaaa
hkyaaa

Reputation: 100

I can't call Controller Action via Ajax Post

I have some issue about local and published web project differences. I have a .net core mvc project and I tried to save physically save file in controller. I get file from file selector then pass my FileModel. But in locally everthing is fine, I could access controller than save file, but After published on server, than I tried to upload file I coudldnt access to controllers method.

My ajax post code here: (FileUpdateIndex.cshtml)

 if (form != null)
            {
                $.ajax({
                    url:"SavePhysicalPath",
                    type: 'POST',
                    data: form,
                    processData: false,
                    contentType: false,
                    success: function (result){console.log("success!");}
                    error: function (result){console.log("error!");}
             }

FileUpdateController.cs

        [HttpPost]
        public JsonResult SavePhysicalPath(FileModel model)
        {
...
...
some code
...
        }

İn local everything good, I get console log success! , but in published: (my site www url)/MyProject/FileUpdate/SavePhysicalPath 404 Not Found.

how can I solve this?

Upvotes: 0

Views: 220

Answers (1)

Serge
Serge

Reputation: 43969

Since your website are located at MyProject you have to add MyProject name to your ajax url:

 url:"/MyProject/FileUpdate/SavePhysicalPath",

or you can create a helper function:


function getUrl(controllerAction) {
        var ca = controllerAction.split('/');
        var pathArray = window.location.pathname.split('/');

if (pathArray[1].toLowerCase() != ca[1].toLowerCase()) return "/" + pathArray[1] + controllerAction;
        return controllerAction;
    }

in this case you can use it for your ajax local or production url like:

   url:getUrl("/FileUpdate/SavePhysicalPath"),

This function will be working properly only if you have one level of your subfolders. If you have two or more levels you will have to correct it.

Upvotes: 1

Related Questions