2016-05-25 5 views
1

Ich habe ein Formular, das nur Kontrollkästchen enthält, und ich weiß, dass ich jedes Formular erstellen kann, um Validierungsfehler zu erzwingen. Aber was ich suche, ist ein Fehler, wenn keines der Kästchen überprüft wurde. Wie würde ich das erreichen?Fehlende Formularüberprüfung in der MVC-Anwendung

Ich bin auf der Suche nach einer Fehlermeldung wie: "Sie müssen mindestens eine Eigenschaft auswählen."

Ich sollte klarstellen, dass keines der Felder einzeln benötigt wird, es sollte nur mindestens eine ausgewählte Option sein.


Bearbeiten zur Klarstellung:

Meine Ansicht sieht wie folgt aus etwas:

@using (Html.BeginForm("Method", "Controller", FormMethod.Post, new {id = "id"})) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 

    <div class="form-group"> 
     @Html.LabelFor(model => model.Property1, htmlAttributes: new { @class = "control-label col-md-4" }) 
     <div class="col-md-8"> 
      @Html.CheckBoxFor(model => model.Property1) 
     </div> 
    </div> 
    <div class="form-group"> 
     @Html.LabelFor(model => model.Property2, htmlAttributes: new { @class = "control-label col-md-4" }) 
     <div class="col-md-8"> 
      @Html.CheckBoxFor(model => model.Property2) 
     </div> 
    </div> 
    <div class="form-group"> 
     @Html.LabelFor(model => model.Property3, htmlAttributes: new { @class = "control-label col-md-4" }) 
     <div class="col-md-8"> 
      @Html.CheckBoxFor(model => model.Property3) 
     </div> 
    </div> 
} 

My View-Modell etwa wie folgt aussieht:

public class FormVM 
{ 
    [Display(Name = "One")] 
    public bool Property1 {get;set;} 
    [Display(Name = "Two")] 
    public bool Property2 {get;set;} 
    [Display(Name = "Three")] 
    public bool Property3 {get;set;} 
} 
+0

Bitte geben Sie Ihren Code ein –

+1

Sie müssen Ihr eigenes Validierungsattribut erstellen. Beachten Sie, dass das Hinzufügen des Attributs "[Erforderlich]" nicht notwendig ist, es sei denn, Sie möchten eine benutzerdefinierte Fehlermeldung - ein Bool ist immer erforderlich. –

+0

Ich erkenne das, da das Bool immer etwas ist, aber wie füge ich eine Fehlermeldung bei wenn sie alle falsch sind? – Kasper

Antwort

1

Sie können den IValidatableObject-Schnittstelle auf Ihrem Ansichtsmodell implementieren:

public class FormVM : IValidatableObject 
{ 
    [Display(Name = "One")] 
    public bool Property1 {get;set;} 

    [Display(Name = "Two")] 
    public bool Property2 {get;set;} 

    [Display(Name = "Three")] 
    public bool Property3 {get;set;} 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     var results = new List<ValidationResult>(); 

     if (!(Property1 || Property2 || Property3)) 
     { 
      results.Add(new ValidationResult("You must select at least one property.")); 
     } 

     return results; 
    } 
} 

Der Vorteil dieses zu verwenden, ist, dass diese automatisch ausgelöst werden, wenn Sie ModelState.IsValid in Ihrem Controller rufen, und die Fehlermeldung zu den ModelState Fehlern hinzugefügt.

+0

erhalte ich einen Fehler bei der Ausbeute. Außerdem heißt es: "Keine geeignete Methode zum Überschreiben gefunden." – Kasper

+0

Hmm, es sagt immer noch 'Keine geeignete Methode zum Überschreiben gefunden'. Was vermisse ich? – Kasper

+0

Haben Sie die IValidatableObject-Schnittstelle hinzugefügt? –

1

Wenn diese Validierung sein nur an einem Ort verwendet, dann können Sie es in der Aktion Methode validieren:

Wenn Sie diese Validierung wahrscheinlich häufiger verwenden, würde ich vorschlagen, ein Validierungsattribut zu schreiben.

1

Da die Frage nicht erwähnt, welche serverseitige oder clientseitige Validierung bevorzugt wurde, gibt es zwei Ansätze.

1) Validierungsserver-Seite (ohne ModelState.AddModelError):

Controller.cs

[HttpPost] 
public ActionResult Method(FormVM model) 
{ 
    if (ModelState.IsValid) 
    { 
     // ... other processing code and action returns 
    } 

    if (!(model.Property1 || model.Property2 || model.Property3)) 
    { 
     ViewData["Error"] = "You must select at least one property." // this can be changed with ViewBag 

     // immediately return the same page 
     return View(model); 
    } 
} 

View.cshtml:

<p>@ViewData["Error"]</p> 

2) clientseitige Validierung mit Vanille JS, die ID verwendet, um die erforderlichen Elemente zu identifizieren:

<script type="text/javascript"> 
var check1 = document.getElementById("check1").value; 
var check2 = document.getElementById("check2").value; 
var check3 = document.getElementById("check3").value; 

if (!(check1 || check2 || check3)) 
{ 
    document.getElementById("error").innerHTML = "You must select at least one property."; 
} 
else 
{ 
    document.getElementById("error").innerHTML = ''; 
} 
</script> 

<div class="form-group"> 
     @Html.LabelFor(model => model.Property1, htmlAttributes: new { @class = "control-label col-md-4" }) 
     <div class="col-md-8"> 
      @Html.CheckBoxFor(model => model.Property1, htmlAttributes: new { @id = "check1" }) 
     </div> 
    </div> 
    <div class="form-group"> 
     @Html.LabelFor(model => model.Property2, htmlAttributes: new { @class = "control-label col-md-4" }) 
     <div class="col-md-8"> 
      @Html.CheckBoxFor(model => model.Property2, htmlAttributes: new { @id = "check2" }) 
     </div> 
    </div> 
    <div class="form-group"> 
     @Html.LabelFor(model => model.Property3, htmlAttributes: new { @class = "control-label col-md-4" }) 
     <div class="col-md-8"> 
      @Html.CheckBoxFor(model => model.Property3, htmlAttributes: new { @id = "check3" }) 
     </div> 
    </div> 
</div> 
<div id="error"></div> 
Verwandte Themen