我在名为ajax.aspx页面的页面中有以下脚本:
<script type="text/javascript">
$(document).ready(function () {
var nameFoundMessage = $('#nameFoundMessage');
var nameInput = $('#name');
nameFoundMessage.hide();
nameInput.blur(function () {
if ($(this).val()) {
$.getJSON('Services/ArtistFound.aspx?' + escape($(this).val()), function (results) {
if (results.available) {
if (nameFoundMessage.is(':visible')) {
nameFoundMessage.html('The name was found');
}
}
else {
nameFoundMessage.show();
nameFoundMessage.html('The name was not found');
}
});
}
});
});
</script>
该页面有一个id为“name”的输入字段,当我模糊它进入一个服务文件夹,其中有另一个aspx页面ArtistFound.aspx并且在该页面加载时,我有以下内容:
Response.ContentType = "application/json";
string name = Request.QueryString.ToString();
string output = string.Empty;
name = db.Names.Single(x => x.Name== name).Name;
if(name == null)
{
output = "{available:false}";
}
else
{
output = "{available:true}";
}
Response.Write(output);
}
当我运行页面并模糊输入时,它会显示以下内容:
无法加载资源:服务器响应状态为500(内部服务器错误)
我试过../ Services / ArtistFound.aspx ...和/Services/ArtistFound.aspx ...,但它仍然给我同样的错误。
答案 0 :(得分:1)
你想:
name = db.Names.FirstOrDefault(x => x.Name== name);
if(name != null && name.Name != null)
{
output = "{available:true}";
}
else
{
output = "{available:false}";
}
如果找不到它,则返回null,而不是像Single()那样抛出异常。
我还建议您使用ASHX处理程序而不是ASPX页面来执行此调用。 要做到这一点,你只需在visual studio中添加一个'Generic Handler'文件,然后就可以用这个替换ProcessRequest方法:
public void ProcessRequest(HttpContext context)
{
string name = context.Request.QueryString.ToString();
string output = string.Empty;
name = db.Names.FirstOrDefault(x => x.Name == name);
if (name != null && name.Name != null)
{
output = "{available:true}";
}
else
{
output = "{available:false}";
}
context.Response.ContentType = "application/json";
context.Response.Write(output);
}