在我的mvc网络应用程序中,我有员工用来提交假期请求的表格。如果选择了过去的日期,是否可以显示警告消息?类似于确认消息,但我仍然希望员工能够选择过去的日期。
这是我在“视图”中的表单:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal" style=" position:relative; top:20px;border-radius: 0px; border-color: #F47B20; border-style: solid; border-width: 5px; background-repeat: no-repeat; background-position: right; padding: 60px; background-size: contain; background-color:white ">
<h2 align="center">Holiday Request Form</h2>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.StartDate, "Start Date", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StartDate, "Start Date", new { htmlAttributes = new { @class = "form-control", autocomplete = "off" } })
@Html.ValidationMessageFor(model => model.StartDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.FinishDate, "Finish Date", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FinishDate, new { htmlAttributes = new { @class = "form-control", autocomplete = "off" } })
@Html.ValidationMessageFor(model => model.FinishDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.HoursTaken, "Hours Requested", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.HoursTaken, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.HoursTaken, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" class="btn btn-warning" />
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(document).ready(function () {
$('input[type=datetime]').datepicker({
dateFormat: "dd/M/yy",
changeMonth: true,
changeYear: true,
yearRange: "-70:+70"
});
});
</script>
}
控制器:
[Authorize(Roles = "Admin,User,SuperUser")]
public ActionResult Create()
{
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FullName");
return View();
string name = Session["Name"].ToString();
var EmployeeIDCatch = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.EmployeeID);
}
// POST: HolidayRequestForms/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RequestID,StartDate,FinishDate,HoursTaken,Comments,YearCreated,MonthCreated,DayCreated,YearOfHoliday,Approved,SubmittedBy,ApprovedBy")] HolidayRequestForm holidayRequestForm)
{
if (ModelState.IsValid)
{
if (Session["Name"] == null)
{
TempData["msg"] = "Your Session Expired - Please Login";
return RedirectToAction("Login", "Account");
}
string name = Session["Name"].ToString();
var employeeID = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.EmployeeID).FirstOrDefault();
holidayRequestForm.EmployeeID = employeeID;
var submittedby = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.Email).FirstOrDefault();
holidayRequestForm.SubmittedBy = submittedby;
db.HolidayRequestForms.Add(holidayRequestForm);
db.SaveChanges();
SendMailToAreaManager();
SendMailToManager();
SendMailToAdmin();
return RedirectToAction("Index", "Calendar");
}
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FullName", holidayRequestForm.EmployeeID);
return View(holidayRequestForm);
}
答案 0 :(得分:4)
您可以使用jQuery完成所有工作。这是代码:
HTML:
<input placeholder="dd/mm/yyyy" id="datepicker"/>
<p id="warning" style="color:orange"></p>
jQuery:
$( function() {
$( "#datepicker" ).datepicker({
onSelect: function(date) {
let dateNow = new Date();
let dateSelect = new Date(date);
dateNow.setHours(0,0,0,0);
if(dateNow > dateSelect){
$("#warning").show().text("The date in the past is selected")
}else{
$("#warning").hide()
}
}
});
});
答案 1 :(得分:1)
您可以为此案例创建一个自定义属性。
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class CheckDateAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime date = (DateTime)value;
if (date > DateTime.Now)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(ErrorMessage);
}
}
}
并设置为您的媒体资源:
[CheckDate(ErrorMessage = "Date should not past")]
public string StartDate { get; set; }
如果您不想更改模型类,可以这样做
public class EmployeeMetaData
{
[CheckDate(ErrorMessage = "Date should not past")]
public string StartDate { get; set; }
}
[MetadataType(typeof(EmployeeMetaData))]
public partial class Employee
{
}