2014-01-14 74 views
5

我需要獲取自定義ASP.NET MVC幫助器的工作驗證。如何驗證自定義ASP.NET MVC幫手

助手

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) 

我好像驗證,但不會出現任何消​​息。 enter image description here

任何線索?

回答

5

您的文本字段的名稱是ProductUID_autocomplete,但您的ValidationMessageFor應該顯示錯誤消息綁定到ProductUID

因此,請確保您有約束力的錯誤消息相同屬性:

@Html.ValidationMessage("ProductUID_autocomplete") 

看來,任何自定義邏輯,你可能需要驗證此字段的ProductUID_autocomplete項下注入錯誤的ModelState

這就是說,爲什麼不只是在您的自定義幫助器中調用ValidationMessage幫助器?通過這種方式,您可以在視圖中輸入更少的內容,而邏輯以及後綴_autocomplete的名稱將僅保留在幫助器中。

+0

非常感謝Darin!你總是幫忙!上帝保佑你,男人! –