【问题标题】:MVC Required Validation not workingMVC 必需的验证不起作用
【发布时间】:2015-09-30 07:20:46
【问题描述】:

我的模型是:-

public class instrument
{
    [Display(Name = "Id")]
    public string Id { get; set; }

    [Display(Name = "Instrument Id")]
    public String InstrumentId
    {
        get;
        set;
    }      

    [Display(Name = "Manufacturer"),Required(AllowEmptyStrings=false)]
    public List<string> manufacturer
    {
        get;
        set;
    }
 .....
 .....
}

我的观点有这些

        <div class="form-group">
            @Html.LabelFor(model => model.manufacturer[0], htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.manufacturer[0], new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.manufacturer[0], "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.manufacturer[1], htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.manufacturer[1], new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.manufacturer[1], "", new { @class = "text-danger" })
            </div>
        </div>

当我向控制器提交表单时(没有在这两个文本框中输入任何值),列表制造商包含两个空字符串。我想验证这些。因为 Model.IsValid 总是为真,因为制造商有两个空字符串。

【问题讨论】:

  • 您想要的实际验证是什么([Required] 不适用于集合) - 您是否要确保集合中的每个项目都不是 null/空字符串?
  • 是的。我想这样做。
  • 那么属性manufacturer 需要是List`,其中Manufacturer 是一个包含属性(例如)string Name 的类,该属性用[Required] 属性修饰。但是您不应该以这种方式生成您的视图。相反,使用for 循环
  • 好的。但我认为这些是制造商名称的简单字符串。因为我将它们保存在 documentDB 中。谢谢。
  • [Required] 验证您应用它的属性不是null。由于您的List&lt;string&gt; 永远不会是null,所以它总是通过验证

标签: asp.net-mvc c#-4.0 asp.net-mvc-5 data-annotations asp.net-mvc-5.1


【解决方案1】:

您可以使用所需的属性来验证您的模型,例如 [Display(Name = "Id")],以显示模型中所有属性的 ID

【讨论】:

    【解决方案2】:

    制造商可以在模型中拥有自己的类:

    public class Instrument
    {
        [Display(Name = "Id")]
        public string Id { get; set; }
    
        [Display(Name = "Instrument Id")]
        public String InstrumentId { get; set; }      
    
        public List<Manufacturer> Manufacturer { get; set; }
    }
    
    public class Manufacturer
    {
        [Display(Name = "Manufacturer")]
        [Required(AllowEmptyStrings=false)]
        public string Name
        {
            get;
            set;
        }
    }
    

    在视图中:

    @Html.EditorFor(m => m.Manufacturer[0].Name, new { htmlAttributes = new { @class = "form-control" } })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 2021-05-22
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多