Alex
Alex

Reputation: 1061

Calling ASP MVC 3 Controller from View via getJSON

I'm using jQuery validation plug-in. To check if a username already exists, I've done this in my view:

$.validator.addMethod('usernameExists', function (value) {
    var data = {};

    data.username = $('#Username').val();

    $.getJSON('/Account/CheckUsername', data, function (result) {
        if (result.exists == 'true')
            return true;
        else
            return false;
    });

    return false;
}, 'Username already exists.');

And in my AccountController, I have:

public JsonResult CheckUsername(string username)
{
    string test = "false";

    return Json(test);
}

I've put a breakpoint into "CheckUsername" and it never comes there, but it comes to the "getJSON" call (I've tried it). Can someone tell me what am I doing wrong? Obviously, something is wrong with "getJSON"... but what???

Upvotes: 0

Views: 9487

Answers (3)

user3652614
user3652614

Reputation: 11

$(function () {
    $.getJSON("your path here", { username: $('#Username').val() }, function (data) {
        //logic goes here
    });
});

Upvotes: 1

Daniil Novikov
Daniil Novikov

Reputation: 440

First, try to call the this action directly from browser: like http://localhost:1212/Account/CheckUsername. If there an error in action you will see it. I assume that you should use JsonRequestBehavior.AllowGet to make it work, since getJSON send HTTP GET.

return Json(test, JsonRequestBehavior.AllowGet);

Upvotes: 2

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21376

try using,

 $.getJSON('@Url.Action("CheckUsername", "Account")', data, function (result) {

further more using "/Account/CheckUsername" will be a trouble for you when you are going to deploy the web site.

Upvotes: 0

Related Questions