Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

404 Not Found Ajax jquery MVC

I created an MVC3 project in Visual Studio 2013. The view engine is razor.First I write jquery.ajax in @section Scripts {} in view(cshtml) it works fine. But I seperate script in .js file and debugging I get error : (debugging IIS Express)

IIS 8.0 Detailed Error - 404.0 - Not Found ... More Information: This error means that the file or directory does not exist on the server. Create the file or directory and try the request again.
..

My jquery function(archive.js) :

jQuery.AjaxGetProjects = function (dropdownId, detailDropDownId, authorized) {

var projectId = $(dropdownId).val();
if (projectId != null && projectId != '') {
    var url =
    $.ajax({
        type: "POST",
        url: '@Url.Action("GetProjects", "Archive")',
        data: {
            'projectId': projectId,
            'authorized': authorized
        },
        success: function (departman) {
            var length = 0;
            $(detailDropDownId).empty();
            $.each(departman, function (index, proje) {
                length = length + 1;
                $(detailDropDownId).append($('<option/>', {
                    value: proje.Value,
                    text: proje.Text,
                    selected: proje.Selected
                }));
            });
            if (length == 2) {
                $(detailDropDownId).trigger('change');
            }

        },
        error: function (xhr, ajaxOptions, thrownError) {
            // bu kısımda eğer ajax işlemi başarısız ise
            // hata mesajı verebiliriz.
            alert(xhr.responseText);
        }
    });
}

}

Controller :

public class ArchiveController : BaseController
{
   ...
   public ActionResult GetProjects(int projectId, bool authorized)
    {

        IArchive arch = WcfServiceHandler.GetDmsService<IArchive>();

        List<Poco> list = arch.GetProjects(UserManager.GetUserInfo(), projectId);
        var t = MvcHelper.GetDropDownList<Poco>(list, "NAME", "ID", "");
        return Json(t, JsonRequestBehavior.AllowGet);
    }

I tried this but not work (I got a new error: resource cannot be found ):

  <system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

please help..

like image 592
Adem Aygun Avatar asked Jun 05 '15 08:06

Adem Aygun


2 Answers

javascript cannot use razor syntax so the @Url.Action("GetProjects", "Archive") will not work, try passing in the post URL as a parameter or hardcode it e.g.

jQuery.AjaxGetProjects = function (dropdownId, detailDropDownId, authorized) {

var projectId = $(dropdownId).val();
if (projectId != null && projectId != '') {
var url =
$.ajax({
    type: "POST",
    url: '/Archive/GetProjects',
    data: {
        'projectId': projectId,
        'authorized': authorized
    },
    success: function (departman) {
        var length = 0;
        $(detailDropDownId).empty();
        $.each(departman, function (index, proje) {
            length = length + 1;
            $(detailDropDownId).append($('<option/>', {
                value: proje.Value,
                text: proje.Text,
                selected: proje.Selected
            }));
        });
        if (length == 2) {
            $(detailDropDownId).trigger('change');
        }

    },
    error: function (xhr, ajaxOptions, thrownError) {
        // bu kısımda eğer ajax işlemi başarısız ise
        // hata mesajı verebiliriz.
        alert(xhr.responseText);
    }
});

}

OR

jQuery.AjaxGetProjects = function (dropdownId, detailDropDownId, authorized, postUrl) {

var projectId = $(dropdownId).val();
if (projectId != null && projectId != '') {
var url =
$.ajax({
    type: "POST",
    url: postUrl,
    data: {
        'projectId': projectId,
        'authorized': authorized
    },
    success: function (departman) {
        var length = 0;
        $(detailDropDownId).empty();
        $.each(departman, function (index, proje) {
            length = length + 1;
            $(detailDropDownId).append($('<option/>', {
                value: proje.Value,
                text: proje.Text,
                selected: proje.Selected
            }));
        });
        if (length == 2) {
            $(detailDropDownId).trigger('change');
        }

    },
    error: function (xhr, ajaxOptions, thrownError) {
        // bu kısımda eğer ajax işlemi başarısız ise
        // hata mesajı verebiliriz.
        alert(xhr.responseText);
    }
});
}
like image 25
Stephen Errington Avatar answered Nov 05 '22 15:11

Stephen Errington


You can't use Razor inside a JavaScript file (unless you use something like the RazorJS extension). If you look at your JS in the browser dev tools you'll see that the url outputted is:

url: '@Url.Action("GetProjects", "Archive")',

When it should be:

url: www.yoursite.com/Archive/GetProjects

To fix it, you could make a method call from your view to that JS and pass in the URL, something like:

View:

<script>
    callMethod('@Url.Action("GetProjects", "Archive")');
</script>

Then your JS would be:

function callMethod(url) {
   ....

Or failing that, you code hard code it to be:

url: '/Archive/GetProjects'

But be careful if you're deploying to a site within a sub-directory, that link won't be valid.

like image 185
mattytommo Avatar answered Nov 05 '22 16:11

mattytommo