how to create Register and Login in asp.net mvc.
i want to only logic not all process. please tell me only controller side.
thank you
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajesh GamiRank #30 · 41.5K reputationPosted Mar 30, 2018, 7:27 PM EDT
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(UserAccount account)
{
if(ModelState.IsValid)
{
using (OurDbContext db = new OurDbContext())
{
db.UserAccount.Add(account);
db.SaveChanges();
}
ModelState.Clear();
ViewBag.Message = account.FirstName + " " + account.LastName + " Successfully Registered ";
}
return View();
}
//==== Login
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(UserAccount user)
{
using (OurDbContext db = new OurDbContext())
{
var usr = db.UserAccount.Single(u => u.UserName == && u.Password == user.Password);
if(usr != null)
{
Session["UserID"] = usr.UserID.ToString();
Session["UserName"] = usr.UserName.ToString();
return RedirectToAction("LoggedIn");
}
else
{
ModelState.AddModelError("", "User Name OR Password is wrong. ");
}
}
return View();
}
public ActionResult LoggedIn()
{
if (Session["UserId"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}
Manav PandyaRank #166 · 14.3K reputationPosted Mar 30, 2018, 7:27 PM EDT
Hiten PandyaRank #1,237 · 1.4K reputationPosted Mar 30, 2018, 7:28 PM EDT
Suppose you register yourself in a website then, after successfully getting values of user from your view with validations you need to insert them into database and then get back the latest inserted Id of user in controller for any future processes like to show successful registration message to user.
Now, at the time of login after you get the email or username and password from view to controller.Check that emailId and password combination into database like,
select UserID from tb_User where EmailID = '[email protected]' and password = '123456'
Now if above query returns UserID it means the user is registered and you can set that Id into session for any further processes and show user your dashboard else if you get UserId = 0 menas user is not registered and you can show him view of registration or show some kind of popup with message like you need to register first.
Hope it helps you.
Thanks.
Bhavesh JadavRank #1,731 · 875 reputationPosted Mar 30, 2018, 7:38 PM EDT
I have read below article for register and login functionality in one page using MVC. Please refer it.
- https://www.c-sharpcorner.com/article/multiple-models-in-a-single-view-in-asp-net-mvc/#ReadAndPostComment
In above link you can get logic code for login.I hope it's helpful to you.
Thanks