I've got the following bit of Razor code in MVC5.
<div class="form-group">
<label class="control-label">Name</label>
@Html.TextBoxFor(m => m.Name)
</div>
I now want to make sure that if Name
has an error, the form group div gets a has-error
class. How can I check if the Name property has an error?
Edit: As requested here's a more complete version of the view I'm working with.
@model CaptchaMvc.Models.DefaultBuildInfoModel
<div class="form-group">
@Html.LabelFor(m => m.InputElementId, "Retype the characters in the image", new { @class = "control-label", @for = "CaptchaInputText" })
<div class="input-group">
<span style="padding:0;overflow:hidden;" class="input-group-addon">
@Html.Hidden(Model.TokenElementId, Model.TokenValue)
<img style="margin:-12px" id="@Model.ImageElementId" src="@Model.ImageUrl" alt="Captcha Text" />
</span>
@Html.TextBox(Model.InputElementId, null, new Dictionary<string, object>
{
{"data-val", "true"},
{"data-val-required", Model.RequiredMessage},
{"class", "form-control"},
{"style", "width: 200px;"},
{"placeholder", "Retype captcha"}
})
</div>
</div>
It's a partial view for use with CaptchaMvc. It's included in a form the following way.
@Html.Captcha(6, "_Captcha")
A very simplistic server side check for an error on a field would be:
@ViewData.ModelState.IsValidField("Name")
Returns true/false
, depending on whether the Name field has an errors related to it.
EDIT:
@{
var nameHasError = Html.ValidationMessageFor(x => x.Name) != null && !string.IsNullOrEmpty(Html.ValidationMessageFor(x => x.Name).ToString());
}
@if(ViewData.ModelState.IsValidField(nameof(Model.Property)))
{
// Do some thing
}
else
{
// Do some thing else
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With