Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP.NET MVC, how do I check if a property has an error?

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")
like image 954
Layl Conway Avatar asked Aug 15 '14 04:08

Layl Conway


2 Answers

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());
}
like image 162
Xenolightning Avatar answered Nov 15 '22 03:11

Xenolightning


@if(ViewData.ModelState.IsValidField(nameof(Model.Property)))
{
     // Do some thing
}
else
{
     // Do some thing else
}
like image 27
Mark Macneil Bikeio Avatar answered Nov 15 '22 04:11

Mark Macneil Bikeio