MVC要求验证不起作用

时间:2015-09-30 07:20:46

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

我的模特是: -

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总是成真。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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" } })
相关问题