【发布时间】:2018-03-21 15:03:00
【问题描述】:
我是 ASP.NET MVC 框架的新手,开始我的第一个项目。 我在模型类中使用了数据注释来设置验证消息。但是验证消息会在页面加载时显示。我希望在单击按钮时显示验证消息。我该怎么做?
型号:
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; }
}
}
查看:
@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>
}
控制器:
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(); }
}
}
【问题讨论】:
-
请为您的控制器添加代码,因为这可能与控制器的编码方式有关。
-
@Mocolicious 我已经添加了控制器代码。谢谢!
标签: asp.net-mvc asp.net-mvc-4 data-annotations