How do you check the value that has been entered in an ASP.NET MVC @Html.TextBox and compare it with a value in the database? I want to make an easy login, and want to see if the value that has been entered in the textbox is the same as that in the database
<tr><td>Username</td><td>:</td><td>@Html.TextBox("username", new { @value = ViewBag.username })</td></tr>
I tried things like creating a viewbag and then taking it to the controller, but it didnt seem to work.
Create a viewmodel(a simple class) for this specific UI
public class LoginViewModel
{
[Required]
public string UserName { set;get;}
[Required]
[DataType(DataType.Password)]
public string Password { set;get;}
}
Now in your GET action, create an object of this class and send to your view.
public ActionResult Login()
{
var vm=new LoginViewMode();
return View(vm);
}
Now in our login view(Login.cshtml)which is strongly typed to our LoginViewModel, we will use the TextBoxFor html helper method to render the textboxes for our UserName
and Password
fields.
@model LoginViewModel
@using(Html.Beginform())
{
UserName
@Html.TextBoxFor(x=>x.UserName);
Password
@Html.TextBoxFor(x=>x.Password)
<input type="submit" />
}
This will render a form which has action attribute value set to /YourCotnroller/Login
. now we need to have an HttpPost action method to handle the form posting
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if(ModelState.IsValid)
{
string uName=model.UserName;
string pass=model.Password.
//Now you can use the above variables to check it against your dbrecords.
// If the username & password matches, you can redirect the user to
// another page using RedirecToAction method
// return RedirecToAction("UserDashboard")
}
return View(model);
}
public ActionResult UserDashboard()
{
//make sure you check whether user is logged in or not
// to deny direct access without login
return View();
}
Try like this:
Define model property in your Model class:
public class Login{
[Required]
[Remote("IsUserNameAvaliable", "Home")]
public string username{get;set;}
[Required]
public string password{get;set;}
}
The Remote
attribute that is placed will find the Method/Action with IsUserNameAvaliable
in the controller name Home
.
The remote attribute servers for this purpose in MVC.
public JsonResult IsUserNameAvaliable(string username)
{
//Check if there are any matching records for the username name provided
if (_dbEntity.Users.Any(c => c.UserName == username))
{
//If there are any matching records found
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
string userID = String.Format(CultureInfo.InvariantCulture,
"{0} is not available.", username);
return Json(userID, JsonRequestBehavior.AllowGet);
}
}
Now in your view strongly type the textbox
@model Application.Models.Login
@Html.TextBoxFor(m=>m.username)
@Html.ValidationMessageFor(m=>m.username)
Donot forget to include jquery validation scripts.
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")