I have a view model that contains user details and also extended user details from two different models called User and UserDetails.
In my UsersController I have the following for my Details method –
public ViewResult Details(RegisterViewModel viewModel)
{
User currentuser = context.Users
.Include("UserDetails")
.Where(i => i.UserName == viewModel.UserName)
.First();
currentuser.UserDetails = new UserDetails();
return View(currentuser);
}
In my Details view I start with –
@model TRS.ViewModels.RegisterViewModel
and then try to list the detials from the viewmodel e.g.
<tr>
<td>User Name</td>
<td>@Model.UserName</td>
</tr>
but when I go to the details page for a user I get this error –
Server Error in '/' Application.
Sequence contains no elements
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Sequence contains no elements
Source Error:
Line 37: {
Line 38:
Line 39: User currentuser = context.Users
Line 40: .Include("UserDetails")
Line 41: .Where(i => i.UserName == viewModel.UserName)
I’m obviously doing something wrong but haven’t been able to find what. Any ideas?
There are many things you are doing wrong. The first one is with your LINQ query in which you are searching for a record in your database whose
UserNamematchesviewModel.UserName. But if this query doesn’t return any results when you attempt to call the.First()method at the end you will get an exception. So you could test whether the query returned results:Another thing that is wrong with your code is that your view is strongly typed to
TRS.ViewModels.RegisterViewModelbut yourDetailscontroller action is passing aUsermodel to this view which cannot work. You need to pass a view model to it.Also it is not very clear how is this Details action invoked and what’s the value of the view model passed as argument. Are you sure that you are passing any values to the request? Otherwise all the properties will be empty which might explain by the way why your LINQ query doesn’t find any records.