2010-09-27 74 views
0

我有一个JSON请求,检查服务器是否已在注册过程中使用了用户名。JSON请求期间出错

这是jQuery的电话:

// Instant check availability of the username 
$("#txtUserName").blur(function() { 
    if ($("#txtUserName").val() == "") return; 
    $.ajax({ 
     type: 'post', 
     url: '/Login/CheckUserName', 
     data: "{userName: '" + $("#txtUserName").val() + "'}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function(message) { 
      //Set the spanChecking text letting user know if the uname is available 
      if (message.d == true) { 
       $("#userNameCheck").css({ "color": "red", "font-weight": "bold", "font-size": "small", "padding-left": "5px" }); 
       $("#userNameCheck").text("Non disponibile"); 
      } 
      else { 
       $("#userNameCheck").css({ "color": "green", "font-weight": "bold", "font-size": "small", "padding-left": "5px" }); 
       $("#userNameCheck").text("Disponibile"); 
      } 
     }, 
     error: function(errormessage) { 
      //this is just to see if everything is working. Remove before deploy 
      $j("#userNameCheck").text(errormessage.responseText); 
     } 
    }); 
}); 

,这是控制器的行动,将服务请求

[HttpPost] 
public JsonResult CheckUserName(string userName) { 
    if (Membership.GetUser(userName) == null) 
     return Json(false); 
    else 
     return Json(true); 
} 

反正我不明白为什么我从服务器获取错误500。看看它与提琴手我可以看到,RAW请求是

POST http://localhost:1037/Login/CheckUserName HTTP/1.1 
Host: localhost:1037 
Connection: keep-alive 
Referer: http://localhost:1037/Login/Register 
Content-Length: 22 
Origin: http://localhost:1037 
X-Requested-With: XMLHttpRequest 
Content-Type: application/json; charset=UTF-8 
Accept: application/json, text/javascript, */* 
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3 
Accept-Encoding: gzip,deflate,sdch 
Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4 
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 

{userName: 'sampleuser'} 

但控制器操作接收用户名的空参数。我通过Fiddler看到了这一点,甚至在代码上添加了一个断点。

我在哪里做错了?

编辑

错误返回到客户端

The value cannot be null. Parameter name: username 

请注意,在错误的参数名称没有保留原来的情况。这是成员资格提供者的行为还是应该降低参数的大小写?

回答

0

您正在将请求作为JSON发送,但服务器中没有任何理解或期望这种格式的请求。您有一个控制器操作,预计内容类型为application/x-www-form-urlencoded。试试这个:

data: { userName: $('#txtUserName').val() }, 
contentType: 'application/x-www-form-urlencoded', 

这还具有以下优势照顾的正确的URL编码发送到使用字符串连接你的版本没有达到服务器的参数。

1

尝试使用这种格式的data参数在您的呼叫,而不是:

data: "userName=" + $("#txtUserName").val() 
0

你检查路由,具体的资本?

发布您的路线为这个电话,也许有什么吗?

2

此:

{userName: 'sampleuser'} 

...是不是有效的JSON。这一点,并可能是你想要什么:

{"userName": "sampleuser"} 

RFC的JSON格式的细节。