Robert Ross
Robert Ross

Reputation: 1189

Ajax in mvc view not working

I don't know why my code won't work. I am just trying to make a simple call to one of my controllers and get a json result in return.

The script in my view looks the following :

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
            var serviceURL = '/WorkRolesController/checkNumRoles';

            $.ajax({
                type: "POST",
                url: '@Url.Action("checkNumRoles", "WorkRolesController")',
                dataType: "json",
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data, status) {
                alert(data);
            }

            function errorFunc() {
                alert('error');
            }
        });
</script>

And here is how the (simplified) action method in the controller looks :

[HttpPost]
    public ActionResult checkNumRoles()
    {

        return Json("skat", JsonRequestBehavior.AllowGet);
    }

I currently get an alert with the string 'error' in it, every time I load the page.

What am I missing?

Upvotes: 1

Views: 2078

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

You don't need to include the Controller suffix when providing the controller name in the Url.Action. Try this:

url: '@Url.Action("checkNumRoles", "WorkRoles")',

Also note JsonRequestBehavior.AllowGet is redundant as it's a POST request only Here's a complete example:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: '@Url.Action("checkNumRoles", "WorkRoles")',
            dataType: "json",
            success: function(data, status) {
                alert(data);
            },
            error: function() {
                alert('error');
            }
        });
    });
</script>
[HttpPost]
public ActionResult checkNumRoles()
{
    return Json("skat");
}

Upvotes: 2

Related Questions