我將介紹ASP.NET MVC 4 Web應用程序。如果名稱重複,則無法在數據庫中找到某個項目
我有一個用戶數據庫(實體框架)。我可以通過他的姓名或電子郵件或兩者來添加,刪除或搜索用戶。例如,如果我搜索「George」並且表中只有一個George,它就可以正常工作。但是如果有更多的用戶使用這些名字,我需要向他們展示。 Insted我有一個例外。
這裏是我的控制器的搜索行動:
[HttpPost]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ActionResult Search(User userinfo)
{
const string noResult = "Search Result Not Found";
var itemforSearch = new User();
using (var uc = new UserContext())
{
if (userinfo.Name == null && userinfo.Email == null)
{
List<User> users;
users = uc.UserList.ToList();
return new JsonResult { Data = null };
}
if (userinfo.Name != null)
{
itemforSearch = uc.UserList.SingleOrDefault(o => o.Name == userinfo.Name);
return GetSearchedItem(noResult, itemforSearch);
}
else
{
if (userinfo.Email != null)
{
itemforSearch = uc.UserList.SingleOrDefault(o => o.Email == userinfo.Email);
return GetSearchedItem(noResult, itemforSearch);
}
}
}
return View(itemforSearch);
}
private ActionResult GetSearchedItem(string noResult, Models.User itemforSearch)
{
if (itemforSearch != null)
{
return new JsonResult { Data = itemforSearch };
}
else
{
throw new Exception("User with provided information was not find");
}
}
這裏是我的腳本點擊後的作品「搜索」按鈕:
<script type="text/javascript">
function DbSearch() {
// Get some values from elements on the page:
var serchedName = $("input[name='SearchName']").val(),
searchedEmail = $("input[name='SearchEmail']").val();
var user = { Name: serchedName, Email: searchedEmail };
$.ajax(
{
type: "POST",
url: "Search",
data: JSON.stringify({ userinfo: user }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSearchSuccess,
error: OnError
});
}
function OnSearchSuccess(data) {
var tableContent = "<tr>" +
"<td>" + data.UserId + "</td>" +
"<td>" + data.Name + "</td>" +
"<td>" + data.Email + "</td>" +
"</tr>";
$('#UserTable').empty();
$("#UserTable").append(tableContent);
$("#UserTable").fnDraw();
}
function OnError(data) { }
</script>
其實我覺得這個問題是在我的LINQ表達,當我使用SingleOrDefault
(我得到{System.InvalidOperationException}但我該如何解決它?
我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 – 2014-09-28 18:12:29