dimanche 28 juin 2015

Don't fire a required validator for

I have the following model:

public class Model1
{
    [Required(ErrorMessage="E1")]
    public string Name { get; set; }
    [Required(ErrorMessage="E2")]
    [RegularExpression(".+\\@.+\\..+")]
    public string Email { get; set; }
    [Required(ErrorMessage="E3")]
    public bool WillAttend { get; set; }
}

controller action:

    public ActionResult Model1()
    {
        Model1 m = new Model1();
        return View(m);
    }

and view:

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Model1</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

problem is required validator for WillAttend property does not work. Even in action method, ModelState.IsValid is true. Why and how to do WillAttend is required ?

Aucun commentaire:

Enregistrer un commentaire