C# 将所需添加到LabelFor

C# 将所需添加到LabelFor,c#,asp.net-mvc,C#,Asp.net Mvc,我有以下代码: @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } }) 我正在寻找一种方法,将html属性required添加到其中,这样用户在没有字段填充的情况下就不能提交。但现在确定怎么办?我知道简单的方法是添加必需的,但不知道如何添加,我尝试了@html“required”,但没有任何运气 编辑: Answare=required=“”您可以添加到

我有以下代码:

@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
我正在寻找一种方法,将html属性
required
添加到其中,这样用户在没有字段填充的情况下就不能提交。但现在确定怎么办?我知道简单的方法是添加
必需的
,但不知道如何添加,我尝试了
@html“required”
,但没有任何运气

编辑: Answare=required=“”

您可以添加到模型属性中:

[Required(ErrorMessage = "Title is required")]
public string Title { get;set; }
并将ValidationMessageFor添加到cshtml中:

@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.Model)
然后将模型验证添加到控制器方法中。它是asp.net mvc的标准管道


您还可以实现将所需属性添加到html代码中

您将需要此文件进行客户端验证

"~/Scripts/jquery.js"
, "~/Scripts/jquery.validate.js"
,"~/Scripts/jquery.validate.unobtrusive.js"
而对于控制器上的服务器端,即使有些禁用了javascript,也必须这样做

if (ModelState.IsValid)
如上所述,使用注释

[Required(ErrorMessage = "Title is required")]
public string Title { get;set; }
使用fluentapi

    public class ClassNameConfiguration : EntityTypeConfiguration<ClassName>
    {
        public ClassNameConfiguration()
        {
            Property(x => x.Title).IsRequired();
        }
    }
公共类ClassNameConfiguration:EntityTypeConfiguration
{
公共类名称配置()
{
属性(x=>x.Title).IsRequired();
}
}

谢谢!这就是我需要的@AgentFire在这种情况下,用户可以手动装箱post请求并保存不带标题的实体。从安全点看是错误的。请将所需属性添加到模型属性