ASP.NET MVC - Determine if field has an error in Razor view

Viewed 3967

I'm working on an input form in ASP.NET MVC. My input form looks like this:

@using (Html.BeginForm("Result", "Contact", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role="form" }))
{
  <h4>What do you want to tell us?</h4>
  @Html.ValidationSummary(true, "", new { @class = "text-danger" })

  <div class="form-group label-floating">
    <label class="control-label" for="Subject">Subject</label>
    <input class="form-control" id="Subject" name="Subject" type="text">
  </div>

  <div class="form-group">
    <input type="submit" value="Send" class="btn btn-primary btn-raised" />
  </div>

  @Html.AntiForgeryToken()
}

My model behind this form looks like this:

public class ContactModel
{
  [Required(ErrorMessage="Please enter the subject.")]
  [Display(Name="Subject")]
  public string Subject { get; set; }
}

I want to conditionally apply classes and structure based on whether or not the Model is valid. I also want to do it per field. My question is, in Razor, how do determine if the "Subject" property is valid, or if it has errors? Thanks!

3 Answers

While ValidationMessageFor is the standard approach for displaying validation errors, the following code does exactly what you asked for and can be useful in rare circumstances:

@if (!ViewData.ModelState.IsValidField("Subject"))
{
    //not valid condition
}
Related