1

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?

1
  • try url: '/WorkRoles/checkNumRoles' Commented Jan 26, 2017 at 14:35

1 Answer 1

2

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This was the problem... Oh, God... :D
No problem, glad to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.