单击mvc4中的按钮时不显示验证消息

时间:2015-11-29 12:17:59

标签: c# asp.net-mvc-4 razor

我创建了一个登录页面,如果用户在点击按钮时没有输入用户名和密码,我希望它显示验证消息,我已编写如下代码

Homecontroller.cs

  public ActionResult Login()
    {
        // ViewBag.Message = "Your contact page.";

        return View();
    }


    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(logintable p)
    {
       abEntities db = new abEntities();
        List<sp_logindata_Result> data = db.sp_logindata(p.Username, p.Password).ToList();

        Session["LogedUserID"] = data.First().UserID.ToString();
        Session["UserNme"] = data.First().FullName.ToString();
        int typeVal = data.First().Usertype;

        if (typeVal == 1)
        {
            return RedirectToAction("page1");
        }
        else if (typeVal == 2)
        {
            return RedirectToAction("page2");
        }
        else
        {
            return RedirectToAction("Error");
        }



        return View(data);
    }

logintable.cs

 public partial class logintable
{
    public logintable()
    {
        this.PerformanceDetails = new HashSet<PerformanceDetail>();
        this.EvaluationDetails = new HashSet<EvaluationDetail>();
    }
    public string FullName { get; set; }
     [Required(ErrorMessage = "Employee name is required")]
    public string Username { get; set; }
     [Required(ErrorMessage = "Password is required")]
    public string Password { get; set; }

    public virtual ICollection<PerformanceDetail> PerformanceDetails { get; set; }
    public virtual ICollection<EvaluationDetail> EvaluationDetails { get; set; }
}

login.cshtml

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div>
    <fieldset>
        <legend>Login</legend>

        <div class="editor-field">
            @Html.TextBoxFor(u => u.Username)
            @Html.ValidationMessageFor(u => u.Username)
        </div>
        <div class="editor-label">
            @Html.LabelFor(u => u.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(u => u.Password)
            @Html.ValidationMessageFor(u => u.Password)
        </div>

        <input type="submit" value="Log In" />
    </fieldset>
</div>

}

我在这里缺少什么,所以它没有显示消息。

1 个答案:

答案 0 :(得分:0)

那不会自动发生

您需要至少遵循以下步骤:

  1. 将验证规则添加到您的模型[您已经完成]
  2. 添加将负责客户端验证的脚本(不引人注意的验证)[必需]。

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
    
  3. 在BundleConfig.cs文件中,在App_Start文件夹

    下添加软件包
    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
    "~/Scripts/jquery.unobtrusive*", 
     ~/Scripts/jquery.validate*"));