2010-09-27 29 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格式的細節。