Hi guys,
I am back after long interval with some new and exciting stuffs.
Today i will explain how can we write our custom code in ASP.NET MVC for user account management like Login, User Registration, Password Change, Password Reset etc. Will we see each one of them in a series of post.
MVC Login:
Step 1: Create a new project from visual studio and select MVC template as project type.
Step 2: In the solution explorer you will see a Models folder. Right click and add a new class named “UserAccountModel.cs”
Step 3: Create a new public class named “Login” in UserAccountModel.cs with below definition.
Step 4: Goto Controllers folder in solution explorer, right click and add new controller named “Account Controller”. Select scaffolding template as “Empty MVC controller” as we will be creating our own template.
Step 5: Add below lines of code in new Account controller created.
you might see that I have created 2 methods (overloaded methods) with same name “Login”. The earlier 1 is for HttpGetRequest i.e this controller will help MVC to render Login model in UI (html) and later one will provide actual login functionality during login process.
Step: 5: Right click in “public ActionResult Login(Login loginDetails)” overloaded Login function and Add new view. Select strongly typed view and select Login model that we have already created. This strongly type Login model will help Razor view engine to generate the html layout.
Step 6: Navigate to View folder in solution explorer and see “Login.cshtml” as below.
Step 7: I have created a stored procedure named “dbo.usp_Login” in my database to validate the user during login process.I encrypted password before storing this into database to implement some sort of security. I had to add this SP in my Entity Framework model I included in project and this SP will be treated as a function to EF.
See how I validate and capture returning value from SP in controller code above. I am using form authentication which is a very popular mechanism in .NET and I saved username in cookie for further usage in project.
Step 8: Run the project and see “Account/Login” view which looks like below. You can provide some cool css to make it look good.
That’s all. You are done !! Isn’t is very cool? Looking forward for your valuable recommendation and feedback.