2016-03-02 23 views
1

我有這個簡單的自動完成與JSON結果。假設沒有適合顯示div的值(所以用戶可以創建一個新實體),並且我不明白爲什麼它不顯示隱藏的div。isNaN然後顯示不工作

public JsonResult GetSubjectsName(string term) 
{ 
    var results = db.subjects.Where(s => term == null || s.SubjectName.ToLower().Contains(term.ToLower())) 
     .Select(x => new 
     { 
      id = x.SubjectId, 
      value = x.SubjectName 
     }).Distinct().ToList(); 
     return Json(results, JsonRequestBehavior.AllowGet); 
    } 
​​
$("#term").autocomplete({ 
    source: function (request, response) { 
     $.ajax({ 
      url: "GetSubjectsName", 
      data: "{'term': '" + request.term + "' }", 
      dataType: 'json', 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      dataFilter: function (data) { return data; }, 
      success: function (data) { 
       response($.map(data, function (item) { 
        if (isNaN(item.id)) { 
         $("#divId").show("slow"); 
        }; 
        return { 
         label: item.value, 
         value: item.value, 
         id: item.id, 
        } 
       })); 
      } 
     }); 
    }, 
    minLength: 2, 
}); 

回答

1

您在返回的科目List,我以爲一切都將有一個id

你的支票,而不是if isNaN,可能是檢查length: -

success: function(data) { 

    if (!data.length) { 

    $("#divId").show("slow"); 

    } else { 

    response($.map(data, function(item) { 
     return { 
     label: item.value, 
     value: item.value, 
     id: item.id, 
     } 
    })); 

    } 
} 
+0

感謝你的幫助,它的做工精細。 – Danny

+0

很高興我能幫到你。 – BenG