I'm going to speak about ASP.NET MVC 4 Web Application.
I have a database of users (Entity Framework). I can add, delete or search for user by his name or email, or both. It works fine if, for example, I search for "George" and there is only one George in the table. But if there are more users with these name, I need to show them all. Insted I have an exception.
Here is my controller's action for Search:
[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");
}
}
Here is my script that works after clicking "Search" button:
<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>
Actually, I think the problem is in my LINQ expression, when I use SingleOrDefault
(I got {System.InvalidOperationException} but how can i fix it?