Sar*_*aiz 1 c# entity-framework asp.net-mvc-4
我正在制作一个注册表格.它有一个名为的文本框UserName.我想点击按钮检查用户名可用性.我正在使用asp.net MVC4.点击按钮我调用了以下功能.如果用户名已在数据库中,则返回成功,但如果用户名不在数据库中,则不返回.它在执行查询时停止.这是我的功能代码.如果用户名不可用,我想返回false.
public JsonResult CheckUserName()
{
string userName = Request["UserName"];
var cx = new PostAdPage.Models.mydbEntities3();
// Stops at this line if username is not available
var u = cx.signups.First(x => x.username.Equals(userName));
if (u.username.Equals(userName))
{
return this.Json(true, JsonRequestBehavior.AllowGet);
}
else
{
return this.Json(false, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
当没有找到结果时,对First的调用会抛出异常,所以我想这就是为什么它会在你的情况下停止执行.
您应该调用FirstOrDefault,如果没有匹配的用户名,则返回null.
var u = cx.signups.FirstOrDefault(x => x.username.Equals(userName));
if (u != null) //Found
return this.Json(true, JsonRequestBehavior.AllowGet);
else //Not found
return this.Json(false, JsonRequestBehavior.AllowGet);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
173 次 |
| 最近记录: |