2014-09-28 36 views
0

我將介紹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}但我該如何解決它?

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 – 2014-09-28 18:12:29

回答

2

當使用SingleOrDefault時,你會得到一個外部當這些數據具有符合您的條件多行上,這個屬性也文檔http://msdn.microsoft.com/en-us/library/vstudio/bb342451.aspx

中如果你想返回匹配你的要求,你應該使用.where()方法用戶的列表說明。

像這樣:itemforSearch = uc.UserList.Where(o => o.Name == userinfo.Name).ToList();

或者,如果你只是想你可以使用一個.firstOrDefault()匹配一行。

喜歡這個:itemforSearch = uc.UserList.FirstOrDefault(o => o.Name == userinfo.Name);


編輯在返回多個用戶結果 控制器和GetSearchedItem功能需要使用List<User>()給多個用戶返回的結果進一步說明,並在視圖中, function OnSearchSuccess(data)將需要遍歷用戶列表。

下面我修改了控制器來使用List,但是我不確定如何使用帶列表的JsonResult,所以如果它不起作用,你將不得不查看它。

[HttpPost] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public ActionResult Search(User userinfo) 
{ 
    const string noResult = "Search Result Not Found"; 
    var itemforSearch = new List<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.Where(o => o.Name == userinfo.Name).ToList(); 
      return GetSearchedItem(noResult, itemforSearch); 
     } 
     else 
     { 
      if (userinfo.Email != null) 
      { 
       itemforSearch = uc.UserList.Where(o => o.Email == userinfo.Email).ToList(); 
       return GetSearchedItem(noResult, itemforSearch); 
      } 
     } 
    } 
    return View(itemforSearch); 
} 

private ActionResult GetSearchedItem(string noResult, List<Models.User> itemforSearch) 
{ 
    if (itemforSearch.Count > 0) 
    { 
     // Not sure how JsonResult works with lists but try take a look at this post http://stackoverflow.com/questions/9110724/serializing-a-list-to-json 
     return new JsonResult { Data = itemforSearch }; 
    } 
    else 
    { 
     throw new Exception("User with provided information was not find"); 
    } 
} 
+0

我嘗試了第一個,但我有下一個錯誤:'不能將方法組'ToList'轉換爲非委託類型'MyTask.Models.User'。您是否打算調用該方法?' – TomatoLion 2014-09-28 18:11:51

+0

這可能是因爲'itemforSearch'不是一個列表,如果您希望能夠返回搜索找到的多行,您需要將'itemforsearch'更改爲一個列表'var itemforSearch = new List ();',而且你也必須改變你的視圖來處理一個列表而不是一個單一的對象。 – 2014-09-28 18:17:57

+0

是的,據我所知,我的'itemForSearch'必須是一個列表,但我需要改變我的看法? – TomatoLion 2014-09-28 18:25:32

相關問題