ASP.NET MVC Data Validation - Highlighting Table Rows and Text Fields

In ASP.NET MVC View, I have a couple of checkboxes, one for the email address and one for the phone. I want to make sure that at least one is checked (both can be checked, so the switch is not perfect), and if not, highlight the line with a red border, like a text box with the check functionality ...

I have other fields that are validated correctly, and CSS changes when there is a problem with text fields and text fields. The code below displays a message informing the user that they should indicate their preferred contact information, but do not highlight the line as a problem ...

SCREEN SHOT alt text http://i41.tinypic.com/2hcgfew.jpg

VIEW

<table width="100%"> <tr> <td> <label> How would you like us to contact you? </label> </td> </tr> <tr id="pref_row"> <td> <span class="bold-text">Email: </span>&nbsp; <%=Html.CheckBox("EmailDesired")%> &nbsp; &nbsp; <span class="bold-text">Phone: </span>&nbsp; <%=Html.CheckBox("PhoneDesired")%> </td> </tr> </table> 

CONTROLLER

 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(ContactUs contactus) { ContactUsService svc = new ContactUsService(); // Validation if (!contactus.EmailDesired && !contactus.PhoneDesired) ViewData.ModelState.AddModelError("pref_row", "Please specify a contact preference (phone and/or email)!"); if (ViewData.ModelState.IsValid) { MessageModel msg = svc.SendRequest(contactus); return RedirectToAction("Index", msg); } else { return View(); } } 
+4
source share
1 answer

When the HtmlHelper renders, it checks to see if there is any element in the ModelState dictionary that has the same key as the helper itself. if so, the control will be displayed with an attribute class equal to the "input-validation error" that is defined in the css file.
Thus, the style will only be applied to the rendered input elements.

This is my decision:

 <table width="100%"> <tr> <td> <label> How would you like us to contact you? </label> </td> </tr> <tr class="<%=ViewData.ModelState["pref_row"]!= null ? "input-validation-error":"" %>"> <td> <span class="bold-text">Email: </span> <%=Html.CheckBox("EmailDesired")%> <span class="bold-text">Phone: </span> <%=Html.CheckBox("PhoneDesired")%> </td> </tr> </table> 
+4
source

Source: https://habr.com/ru/post/1285940/


All Articles