1

Are there a way to check if a given object have an error in ASP.NET MVC 4.

something like

    @Html.PasswordFor(model => model.Username, new { placeholder = Html.DisplayFor(model => model.Username) })
    @if(Html.ErrorFor(model => model.Username)) {
    <small class="error">@Html.ValidationMessageFor(model => model.Username)</small>
}

Update: it is not the model as a whole, but the given element i need to check up on, so f.eks. do mode.Username have an error!

Androme
  • 2,399
  • 4
  • 43
  • 82
  • Have you tried Data Annotations? http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs – Johnie Karr Feb 04 '13 at 16:30

2 Answers2

2

I solved the problem by creating 2 methods.

    public static bool HasErrorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        if (expression == null)
            throw new ArgumentNullException("expression");

        string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
        if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName))
            return false;

        ModelState modelState = htmlHelper.ViewData.ModelState[modelName];
        return modelState.Errors.Count > 0;
    }
    public static MvcHtmlString GetErrorMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        if (expression == null)
            throw new ArgumentNullException("expression");

        string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
        if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName))
            return new MvcHtmlString(null);

        ModelState modelState = htmlHelper.ViewData.ModelState[modelName];
        if (modelState.Errors.Count > 0)
        {
            return new MvcHtmlString(modelState.Errors.FirstOrDefault().ErrorMessage);
        }

        return new MvcHtmlString(null);
    }

and how to use it

<div class="row">
    <div class="six columns">
        @Html.TextBoxFor(model => model.Username, new { placeholder = Html.GetDisplayFor(model => model.Username) })
        @if (Html.HasErrorFor(model => model.Username))
        {
        <small class="error">@Html.GetErrorMessageFor(model => model.Username)</small>
        }
    </div>
</div>
Androme
  • 2,399
  • 4
  • 43
  • 82
0

Use ModeState.IsValid property to check for validness of the model

if(ModelState.IsValid)
{
 //DO update/insertion/deletion
}
else
{
 // return your view
}

to Display Errors. Read this Post for More Info On ModelState Erro Display

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

for Specific property try like this ModelState["yourProperty"]. Gets the model state dictionary object that contains the state of the model and of model-binding validation.

        if (ModelState["yourProperty"].Errors.Count >0) //then error
Community
  • 1
  • 1
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
  • I gave the downvote when you just commented about the ModelState.IsValid, as it showed that you had not read my question, and just anwsered! I don’t know if it is because of i am using MVC 4, but i get the error ” 'System.Web.Mvc.ModelState' is a 'type' but is used like a 'variable'” – Androme Feb 04 '13 at 18:54