0

I have gone through some posts with similar question but haven't find any good solution yet.

I am trying to add a css class in a div by checking that if there exists any error or not. Like below

<div class="form-group m-t-20 @((@Html.ValidationMessage("Email") != null && @Html.ValidationMessage("Email").ToString() != "") ? "has-danger has-error" : "")">

But when I do inspect-element then it seems that @Html.ValidationMessage("Email") is never empty (so has-danger has-error is always added) even though there is not validation message for Email, like

@Html.ValidationMessage("Email") translated to <span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>

So is there a way to check if certain error is present then add a css class ? Also I would apperciate that I donot need to create new class (.cs file) for this small purpose.

PS: I am using Asp.net MVC. And at back-end I add error like this ModelState.AddModelError("Email", "User already exists");

3
  • Why not just use the class names that already are added - field-validation-valid (if its valid) and field-validation-error (if its not) Commented Jun 28, 2017 at 12:03
  • @StephenMuecke I want to add custom css class to div, my structure is <div class="custom-class"><input /></div>. Does class name matter here ? Commented Jun 28, 2017 at 12:07
  • What is the purpose? Why not just style the field-validation-error class? Commented Jun 28, 2017 at 12:09

1 Answer 1

3

If you want to check errors in your model on View you should check ViewData.ModelState property.

Like this:

@if (!ViewData.ModelState.IsValid && ViewData.ModelState["Email"].Errors.Count > 0))
{
   <span>your message<span/>
}

Ternary version:

@((!ViewData.ModelState.IsValid && ViewData.ModelState["Email"].Errors.Count > 0)? "your message": String.Empty)
Sign up to request clarification or add additional context in comments.

8 Comments

On IsValidField its giving me error Compiler Error Message: CS1061: 'System.Web.Mvc.ViewDataDictionary<HospitalManagament.Models.SignupModel>' does not contain a definition for 'IsValidField' and no extension method 'IsValidField' accepting a first argument of type 'System.Web.Mvc.ViewDataDictionary<HospitalManagament.Models.SignupModel>' could be found (are you missing a using directive or an assembly reference?)
@Junaid what version of MVC do you use?
I am using v5.2.3.0.
I tried your solution, but its still adding has-danger has-error in both cases (error and no-error).
@Junaid and what's exactly inside ViewData.ModelState["Email"] with and withour error? Maby you should just ckeck in on String.Empty?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.