gpt4 book ai didi

c# - 必需的属性在 asp.net mvc 中不起作用

转载 作者:行者123 更新时间:2023-12-02 00:10:31 24 4
gpt4 key购买 nike

我有一个简单的强类型 View 。

@model GoldForGold.Models.LogonModel
@{
ViewBag.Title = "Logins";
Layout = "~/Views/Shared/_Layout.cshtml";
}

Logins
@using (Html.BeginForm()) {

Account Information
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName, new { id = "txtUserName" })
@Html.ValidationMessageFor(m => m.UserName)
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { id = "txtPassword" })
@Html.ValidationMessageFor(m => m.Password)
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)

<input type="submit" value="Log On" onclick="getcredentials()" />
}

模型代码在这里。

public class LogonModel
{
[Required(ErrorMessage="please enter username")]
[Display(Name = "User name")]
public string UserName { get; set; }

[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}

即使我不输入用户名和密码,我也看不到任何事情发生。

最佳答案

这是完整的解决方案:

  1. 将以下脚本添加到您的 View 中:

    <script src='@Url.Content("~/Scripts/jquery-1.8.2.js")' type='text/javascript'></script>    
    <script src='@Url.Content("~/Scripts/jquery.validate.js")' type='text/javascript'> </script>
    <script src='@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")' type='text/javascript'></script>
  2. 在 Web.Config 中启用验证:

    <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
  3. 在 View 中添加验证元素:

    @Html.ValidationMessageFor(model => model.UserName)
  4. 向模型元素添加必需的属性。

    [Required(ErrorMessage="please enter username")]
    public string UserName { get; set; }

关于c# - 必需的属性在 asp.net mvc 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19734608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com