MVC 5 + $Post() function not working after hosted on server

跟風遠走 提交于 2019-12-07 19:47:59

问题


I have developed an application in MVC5. Onclick of a link on the View below code gets invoked -

// Code in View File 

$.post('../ControllerName/FunctionName',  //this is your url
            {
                id: image,

            }, function (data) {
                alert("Successfully published");
            }
            ).error(function () {
                alert("Failed to publish");
            });


//Code in Controller

[HttpPost]
    public void ISPPDF(string id)
    {}

Issue that i am facing is the ISPPDF() function gets invoked when i run it through visual studio.However after i hosted my application on server it does not seem to call the function..

I feel there is some issue with the path i have specified -

i also tried specifying path the below ways but no luck!

 /ControllerName/FunctionName
 ControllerName/FunctionName

Any help would be appreciated.

Thanks,


回答1:


Try this as your post method is in view file

$.post('../FunctionName',{ id: image,}, function (data) { alert("Successfully published");}).error(function () {alert("Failed to publish"); });




回答2:


You should never hard-code URLs in MVC.

Instead use @Url.Action.

$.post('@Url.Action("FunctionName", "ControllerName")',  //this is your url

If you need to send parameters, you do it like this:

$.post('@Url.Action("FunctionName", "ControllerName", new { id = Model.ID })',  //this is your url


And there are two important reasons why I recommend this:

1. The chances of mistyping the URL are huge. This Questions proves it, the OP mistyped the URL.
2. Url.Action takes into account your route. If your route changes, Url.Action will know how to build the correct URL. This way you will not have to go through multiple views to change all the hard-coded values.



来源:https://stackoverflow.com/questions/27227489/mvc-5-post-function-not-working-after-hosted-on-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!