Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate custom ASP.NET MVC helper

I need to get working validation of the custom ASP.NET MVC helper.

Helper

public static class AutocompleteHelper
{
    public static MvcHtmlString AutocompleteFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string actionUrl)
    {
        return CreateAutocomplete(helper, expression, actionUrl, null, null);
    }
    public static MvcHtmlString AutocompleteFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string actionUrl, bool? isRequired, string placeholder)
    {

        return CreateAutocomplete(helper, expression, actionUrl, placeholder, isRequired);
    }

    private static MvcHtmlString CreateAutocomplete<TModel, TValue>(HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string actionUrl, string placeholder, bool? isRequired)
    {
        var attributes = new Dictionary<string, object>
                             {
                                 { "data-autocomplete", true },
                                 { "data-action", actionUrl }
                             };

        if (!string.IsNullOrWhiteSpace(placeholder))
        {
            attributes.Add("placeholder", placeholder);
        }

        if (isRequired.HasValue && isRequired.Value)
        {
            attributes.Add("required", "required");
        }

        attributes.Add("class", "form-control formControlAutocomplete");


        attributes.Add("maxlength", "45");


        Func<TModel, TValue> method = expression.Compile();
        var value = method((TModel)helper.ViewData.Model);
        var baseProperty = ((MemberExpression)expression.Body).Member.Name;
        var hidden = helper.Hidden(baseProperty, value);

        attributes.Add("data-value-name", baseProperty);

        var automcompleteName = baseProperty + "_autocomplete";
        var textBox = helper.TextBox(automcompleteName, null, string.Empty, attributes);

        var builder = new StringBuilder();
        builder.AppendLine(hidden.ToHtmlString());
        builder.AppendLine(textBox.ToHtmlString());

        return new MvcHtmlString(builder.ToString());
    }
}

HTML

@Html.AutocompleteFor(x => x.ProductUID, Url.Action("AutocompleteProducts", "Requisition"), true, "Start typing Product name...")
@Html.ValidationMessageFor(x => x.ProductUID)

I seems like validating but no message appears. enter image description here

Any clue?

like image 701
Friend Avatar asked Jan 14 '14 18:01

Friend


People also ask

What is custom validation in MVC?

This validation can be added for both the client side and the server side. You understand that decorating the properties in a model with an Attribute can make that property eligible for Validation. Some of the DataAnnotation used for validation are given below. Required. Specify a property as required.

How does ValidationMessageFor work in MVC?

ASP.NET MVC: ValidationMessageFor ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object. Visit MSDN to know all the overloads of ValidationMessageFor() method.

How many types of validation are there in MVC?

VALIDATION TYPES Normally, we can perform form validation in two ways – either implement in the server-side code i.e. Server-Side Validation or implement these in the client-side i.e. Client-Side Validations.


1 Answers

The name of your text field is ProductUID_autocomplete but your ValidationMessageFor which is supposed to display the error message is bound to ProductUID.

So make sure that you are binding your error message to the same property:

@Html.ValidationMessage("ProductUID_autocomplete")

It appears that whatever custom logic you might have to validate this field is injecting the error under the ProductUID_autocomplete key in the ModelState.

This being said, why not just invoke the ValidationMessage helper inside your custom helper? This way you will have less things to type in your view and the logic with those names being suffixed with _autocomplete will stay inside the helper only.

like image 78
Darin Dimitrov Avatar answered Sep 28 '22 11:09

Darin Dimitrov