I am new to ASP.NET MVC framework, starting my first project. I've used data annotations in my model class for setting validation message. But the validation messages are shown on page load. I want the validation message to be displayed on button click. How can I do this?
Model:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace final_1.Models
{
using System;
using System.Collections.Generic;
public partial class TBL_USER
{
public int USERID { get; set; }
[Required(ErrorMessage = "Please enter user name.")]
public string USERNAME { get; set; }
public string NAME { get; set; }
public int ROLE { get; set; }
[Required(ErrorMessage = "Please enter password.")]
public string PASSWORD { get; set; }
public System.DateTime CREATED_DATE { get; set; }
public int STATUS { get; set; }
}
}
View:
@using (Html.BeginForm("Authorize", "Login", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group has-feedback">
@Html.TextBoxFor(m => m.USERNAME, new { @class = "form-control", @placeholder = "User name", @autofocus = "autofocus" })
@Html.ValidationMessageFor(m => m.USERNAME, "", new { @class = "text-danger" })
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
@Html.PasswordFor(m => m.PASSWORD, new { @class = "form-control", @placeholder = "Password" })
@Html.ValidationMessageFor(m => m.PASSWORD, "", new { @class = "text-danger" })
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8"></div>
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
</div>
}
Controller:
public ActionResult Authorize(TBL_USER userModel)
{
using (MIEntities db = new MIEntities())
{
var userDetails = db.TBL_USER.Where(a => a.USERNAME == userModel.USERNAME && a.PASSWORD == userModel.PASSWORD).FirstOrDefault();
if (userDetails != null)
{
return RedirectToAction("Register", "Student");
}
else
{ return View(); }
}
}
I created two action methods for get
request and for post
request.
[HttpGet]
public ActionResult Authorize()
{
return View();
}
[HttpPost]
public ActionResult Authorize(final.Models.TBL_USER userModel)
{
using (LT_LGCDP_MISEntities1 db = new LT_LGCDP_MISEntities1())
{
var userDetails = db.TBL_USER.Where(a => a.USERNAME == userModel.USERNAME && a.PASSWORD == userModel.PASSWORD).FirstOrDefault();
if(userDetails == null)
{
return View(userModel);
}
return RedirectToAction("Register", "Student");
}
}
It worked!