I read: FormsAuthentication with Razor does not work , but may get some errors from the answer.
using System.Web.Security;
[HttpPost]
public ActionResult Index(LoginModel model, string name, string pw)
{
if (ModelState.IsValid && Membership.ValidateUser(name, pw))
{
if (!String.IsNullOrEmpty(pw) && !String.IsNullOrEmpty(name))
{
try
{
var db = new UsersDBContext();
var Name = (from Users in db.Users
where Users.Name == name && Users.Password == pw
select Users.CustomerId).Single();
if (Name != 0)
{
string myIDString = Name.ToString();
Session["myID"] = myIDString;
return Redirect("/LogModels/Index");
}
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
else
{
}
}
return Redirect("/");
}
The problem is what I'm trying to add
&& Membership.ValidateUser(model.UserName, model.Password)
I get the following error.
Membership does not exist in the current context.
I am new to this, so please explain it in a very simple way, if possible.
Thanks in advance.
EDIT
LoginModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace WebPortalMVC.Models
{
[Table("Users")]
public class UsersModel
{
[Key]
public int Id { get; set; }
[Display(Name = "Name")]
public string Name { get; set; }
[Display(Name = "Password")]
[DataType(DataType.Password)]
public string Password { get; set; }
public int CustomerId { get; set; }
}
public class UsersDBContext : DbContext
{
public UsersDBContext() : base("MySqlConnection")
{
}
public DbSet<UsersModel> Users { get; set; }
}
}
View (not all)
<div id="login">
<h1>Web Portal</h1>
@using (Html.BeginForm())
{
<p>
@Html.TextBox("name", "", new { type = "email", placeholder = "example@email.com" })
</p>
<p>
@Html.Password("pw", "", new { type = "password", placeholder = "Password" })
</p>
<input type="submit" id="loginsubmit" value="Log in" onclick="emptypasswordcheck()" />
}
</div>
</div>
** EDIT 2: ** Added code according to @FreshBM's answer.