提问人:bperniciaro 提问时间:2/27/2023 最后编辑:marc_sbperniciaro 更新时间:2/27/2023 访问量:151
为什么 JQuery Validate 在 ASP.NET Core MVC 中标记为默认必需的输入字段
Why is JQuery Validate marking an input field required by default in ASP.NET Core MVC
问:
我有一个简单的视图,它绑定到一个模型,其中两个属性都不是必需的(并且都是字符串)。默认情况下,生成的标记将该字段标记为必填字段,即使我没有指出此字段在任何地方都是必填字段。[nullable]
Question
它为什么要这样做?我需要做些什么来指示此字段不是必需的?
视图:
@model EightBallModel
@{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Magic 8-Ball Game</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Ask the Magic 8-Ball Anything</h1>
<form method="post" asp-action="GetAnswer" asp-controller="Home">
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(m => m.Question)
@Html.TextBoxFor(model => model.Question, new {@class="form-control"})
@Html.ValidationMessageFor(model => model.Question)
</div>
<button type="submit" class="btn btn-success submit">Ask</button>
<br/><br/>
@Html.ValueFor(x => x.Answer)
</form>
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
</body>
</html>
模型类:
using System.ComponentModel.DataAnnotations;
namespace MagicEightBall.Models
{
public class EightBallModel
{
public string Answer { get; set; } = string.Empty;
public string Question { get; set; } = string.Empty;
}
}
控制器动作方法:
public IActionResult Index()
{
return View(new EightBallModel());
}
结果:
生成的标记:
答:
0赞
bperniciaro
2/27/2023
#1
在 ASP.net 6 及更高版本中,文档建议将字符串属性设置为空,以指示它们可以为空:
public string? Question { get; set; } = string.Empty;
虽然这确实允许提交表单,但仍会出现“问题为必填项”消息。
我允许在不看到错误消息的情况下提交表单的唯一方法是在 Program.cs 文件中禁用此行为:
builder.Services.AddControllers(
options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
评论