Login page code using mvc3:-
(1)First create a model like
mylogin.cs
public class mylogin
{
[Required]
[StringLength(10)]
public string
UserName { get; set;
}
[Required]
public string
PassWord { get; set;
}
}
(2)Create a folder
like DataAccess and with in it create a cs file like DAL.cs
public class DAL
{
static SqlConnection
con = new SqlConnection(ConfigurationManager.ConnectionStrings["111"].ConnectionString);
public static bool UserIsValid(string
username, string password)
{
bool authenticated = false;
string query = string.Format("select * from[fetchlogin] where UserName ='{0}' and
Password ='{1}'", username, password);
SqlCommand cmd = new
SqlCommand(query,con);
con.Open();
SqlDataReader sr = cmd.ExecuteReader();
authenticated = sr.HasRows;
con.Close();
return (authenticated);
}
(3) Create a
controller with in it write
below code:-
public class myloginController : Controller
{
//
// GET: /mylogin/
public ActionResult
Index()
{
return View();
}
[HttpPost]
public ActionResult
Index(mylogin logit)
{
if (ModelState.IsValid)
{
if (DataAccess.DAL.UserIsValid(logit.UserName,
logit.PassWord))
{
FormsAuthentication.SetAuthCookie(logit.UserName,
true);
return
RedirectToAction("Index", "sanshow");
}
{
ModelState.AddModelError("",
"Invalid username or password");
// ModelState.AddModelError("",
"Invalid username or password");
}
}
return View();
}
}
(4)Eventually create a view for this:-
@model sanjibmvcmvc.Models.mylogin
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>mylogin</legend>
<div class="editor-label">
@Html.LabelFor(model
=> model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model
=> model.UserName)
@Html.ValidationMessageFor(model
=> model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model
=> model.PassWord)
</div>
<div class="editor-field">
@Html.EditorFor(model
=> model.PassWord)
@Html.ValidationMessageFor(model
=> model.PassWord)
</div>
<p>
<input type="submit"
value="Create"
/>
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
No comments:
Post a Comment