Hi setwell,
You need to add FirstOrDefault after the linq.
Please refer below sample.
View
Home
<h2>Welcome @Session["UserName"].</h2>
Login
@using (Html.BeginForm("Index", "Login", FormMethod.Post))
{
<table>
<tr>
<th colspan="2" style="text-align:center">Login Page</th>
</tr>
<tr>
<td>@Html.LabelFor(m => m.Username):</td>
<td>@Html.TextBoxFor(m => m.Username)</td>
<td>@Html.ValidationMessageFor(m => m.Username, "", new { @class = "Error" })</td>
</tr>
<tr>
<td>@Html.LabelFor(m => m.Password):</td>
<td>@Html.TextBoxFor(m => m.Password)</td>
<td>@Html.ValidationMessageFor(m => m.Password, "",new { @class ="Error"})</td>
</tr>
<tr>
<th colspan="2" style="text-align:center"><input type="submit" value="Login" /></th>
</tr>
</table>
}
@ViewBag.LoginError
@ViewBag.LoginSuccess
Controller
Home
public ActionResult Index()
{
return View();
}
Login
public class LoginController : Controller
{
LoginDBEntities entities = new LoginDBEntities();
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(User userLogIn)
{
if (ModelState.IsValid == true)
{
var credential = entities.Users.Where(model => model.Username == userLogIn.Username && model.Password == userLogIn.Password).FirstOrDefault();
if (credential == null)
{
ViewBag.LoginError = "Login Failed.";
return View();
}
else
{
Session["UserName"] = userLogIn.Username;
return RedirectToAction("Index", "Home");
}
}
return View();
}
}
Screenshot
