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 t开发者_开发知识库rue;
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???
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);
$(function () {
$.getJSON("your path here", { username: $('#Username').val() }, function (data) {
//logic goes here
});
});
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.
精彩评论