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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19734608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:16:47  来源:igfitidea点击:

required attribute not working in asp.net mvc

asp.net-mvcasp.net-mvc-viewmodel

提问by user2465036

I have a simple strongly-typed 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()" />
}

Model code is here.

模型代码在这里。

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; }
}

I see nothing is happening even when I do not enter username and password.

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

回答by Vahagn Nahapetyan

Here is the complete solution:

这是完整的解决方案:

  1. Add the following scripts to your 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. Enable Validation in Web.Config:

    <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
    
  3. Add validation element in the view:

    @Html.ValidationMessageFor(model => model.UserName)
    
  4. Add Required attribute to you model`s element.

    [Required(ErrorMessage="please enter username")]
    public string UserName { get; set; }
    
  1. 将以下脚本添加到您的视图中:

    <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. 在视图中添加验证元素:

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

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

回答by MRB

For client side validation you need jquery and jquery validation.

对于客户端验证,您需要 jquery 和 jquery 验证。

after that client side validation must be enabled in config:

之后必须在配置中启用客户端验证:

<appSettings> 
...
<add key="ClientValidationEnabled" value="true" /> 
<add key="UnobtrusiveJavaScriptEnabled" value="true" /> 

for server side validation you can check your validation state with:

对于服务器端验证,您可以使用以下方法检查验证状态:

ModelState.IsValid;

回答by Cosmin Cretu

For the record, you can include the following code at the end of your view, to make sure that the [Required]attribute pops up in the user interface:

作为记录,您可以在视图的末尾包含以下代码,以确保[Required]在用户界面中弹出该属性:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

回答by tomRedox

One other thing to be wary of with [Required]is when using it on an integer field, not just when storing a numeric value, but also, say, when storing the id of the selected value of a dropdown/select list.

要注意的另一件事[Required]是在整数字段上使用它时,不仅在存储数值时,而且在存储下拉/选择列表的选定值的 id 时。

[Required]won't work in that situation because an integer property can never be null and so always has a default value of zero. [Required]is checking that the property has a value, and zero is considered a value, so the check will pass.

[Required]在这种情况下将不起作用,因为整数属性永远不能为空,因此默认值始终为零。 [Required]正在检查该属性是否具有值,零被视为值,因此检查将通过。

In that case either declare the property as a nullableinteger instead:

在这种情况下,要么将该属性声明为空的整数:

    [Required]
    public int? LanguageId { get; set; } // note the int is now nullable

or alternatively use the Rangeattribute to stop zero being an acceptable value:

或者使用该Range属性来停止零是一个可接受的值:

    [Range(1, int.MaxValue)]
    public int LanguageId { get; set; }

回答by Ike

My fix for my problem was to use this line of code in the model class.

我对我的问题的解决方法是在模型类中使用这行代码。

using System.ComponentModel.DataAnnotations;

be aware that there is another namespace (Microsoft.Build.Framework) that also supports [Required] annotation.

请注意,还有另一个命名空间 (Microsoft.Build.Framework) 也支持 [Required] 注释。

回答by Jehad87

  • Steps for solution:
  • 解决步骤:

1- Add the scripts to view:

1- 添加脚本以查看:

<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- Enable Validation in Web.Config:

2- 在 Web.Config 中启用验证:

<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

3- Add validation html helper in the view:

3- 在视图中添加验证 html 助手:

@Html.ValidationMessageFor(model => model.UserName)

4- Add Required attribute to your model`s element:

4- 将 Required 属性添加到您的模型元素:

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