Quote for the Week

"Learn to enjoy every moment of your life"

Thursday, August 7, 2014

For Learners: How to show User Name in Welcome screen after user login in Asp.net MVC using Linq to Entities

Basic Knowledge in Asp.net MVC to show user name in Welcome screen

Create table with name "tblUsrs" for login users in UserDB in database.

Run below Sql Query in yOur database

Create database UserDB

USE UserDB
CREATE TABLE tblUsers
(
ID  INT PRIMARY KEY IDENTITY(1,1) ON,
USER_NAME VARCHAR(25),
USER_EMAIL VARCHAR(25),
USER_PASSWORD VARCHAR(25)
)

INSERT INTO tblUsers(USER_NAME,USER_EMAIL,USER_PASSWORD)
VALUES("SANJAY","abc@gmail.com","dotnetcircle")

Now, create a controller with name "AccountController" and Change "Index" Action Method to "Login" Action method.


Create a ADO Entity Data Model in Model Folder with name "UserDbEntities" and specify connection settings then Add table " tblUsers";

Add a class "UserModel" in Model class and write the below properties

public string USER_NAME {get;set;}
public string PASSWORD{get;set;}
public string EMAIL{get;set;}
public string Message{get;set;}

Add  View to "Login" action method with strong type model "UserModel " class.

To Design Login Form- write the below html design in your view

@using Html.BeginForm("Login","Account",FormMethod.POST)
{
<table>
<tr>
<td>
@Html.TextBoxFor(m=>m.EMAIL)
</td>
<td>@Html.TextBoxFor(m=>m.PASSWORD)</td>
</tr>
<tr><td><input type="submit" value="Submit" name="btn">
<table>
@Html.DisplayFor(m=>m.Message)
}

and Add another two Action method like below

[HTTPPOST]
public ActionMethod Login(UserModel model,string btn)
{
if(btn=="Submit")
{
 UserDbEntities entites=new UserDbEntities();
var userDetails=entites.tblUser.Where(m=>m.EMAIL==model.EMAIL && m.PASSWORD==model.PASSWORD).FirstOrDefault();

if(userDetails!=null)
{
model.USER_NAME=userDetails.USER_NAME;

//or we can use session like Session["username"]
return RedirecttoAction("Welcome","Account",model);
}
 model.Message="Invalid Username/Password";
}

return View(model);
}
public ActionResult Welcome(UserModel model)
{

return View(model);
}

Add View to Welcome with strong type class "UserModel"

Write the HTML below design

<div>
<h2>Welcome, @Html.DisplayFor(m=>m.USER_NAME")

or @Session["username"]// if we use session
</div>

then run it and type useername and password which in table. That's it.

Do you like this post, then subscribe to this blog for Interesting concepts.
Do you articles on .net , then mail to dotnetcircle@gmail.com to publish in the bog

No comments: