AJAX Call returning 404(Local) in IIS 7.5 but same works in other IIS

后端 未结 4 2020
傲寒
傲寒 2021-01-31 10:39

Am having the AJAX calls to my controller in my MVC Application

Controller/FunctionName



$.ajax({
        type: \"GET\",
        contentType: \"application/jso         


        
4条回答
  •  半阙折子戏
    2021-01-31 11:34

    That's normal. You have hardcoded the url to your controller action:

    url: '/Controller/FunctionName',
    

    If you deploy your application in a virtual directory in IIS the correct url should be:

    url: '/YourAppName/Controller/FunctionName',
    

    That's the reason why you should absolutely never hardcode urls in an ASP.NET MVC application but ALWAYS use url helpers to generate it:

    url: '@Url.Action("FunctionName", "Controller")',
    

    and if this AJAX call is in a separate javascript file where you cannot use server side helpers, then you could read this url from some DOM element that you are AJAXifying.

    For example let's suppose that you had an anchor:

    @Html.ActionLink("click me", "FunctionName", "Controller", null, new { id = "myLink" })
    

    that you AJAXify:

    $('#myLink').click(function() {
        $.ajax({
            url: this.href,
            contentType: 'application/json; charset=utf-8',
            type: 'GET',
            .
            .
            .
        )};    
        return false;
    });
    

    Notice how we are reading the url from the DOM element which was generated by a helper.

    Conclusion and 2 rules of thumb:

    • NEVER EVER hardcode an url in an ASP.NET MVC application
    • ABSOLUTELY ALWAYS use url helpers when dealing with urls in an ASP.NET MVC application

提交回复
热议问题