2014-03-31 113 views
1

我使用自定义控件(HTML助手)来构建自动完成控件。 它工作得很好,唯一的问题是验证问题。 在客户端,当jquery.validation.js超出图片时,验证正常工作(对于空文本框,它会给出错误消息)。 如果用户从自动填充中选择了某些内容,那么很好。 但是当用户输入只是垃圾,那么HttpPost需要处理垃圾&向用户返回错误信息。 如何?自定义控件上的DataAnnotations属性

另外,我已经看到一个名为Remote的DataAnnotation,它可以管理客户端的验证,是更好的吗?如果是这样,我怎么能在自定义控件上添加DataAnnotaion? 感谢的:)

这里是我的代码: Index.cshtml

@using (Html.BeginForm("Index", "Create")) 
       { 
        @Html.AutocompleteFor(Url.Action("AutoCompleteServiceProviders", "Create"), true, "ex. Shower", c => c.service_id, a => a.name) 
        <input type="submit" id="search" value="" /> 
       } 

AutoComplete.cs

private static MvcHtmlString CreateAutocomplete<TModel>(this HtmlHelper<TModel> helper, string actionUrl, bool? isRequired, string placeholder, params Expression<Func<TModel, object>>[] expression) 
    { 
     var builder = new StringBuilder(); 

     foreach (var item in expression) 
     { 
      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"); 
      } 

      Func<TModel, object> method = item.Compile(); 
      var value = (Object)null; 
      if ((TModel)helper.ViewData.Model != null) 
      { 
       value = method((TModel)helper.ViewData.Model); 
      } 

      var baseProperty = (string)null; 
      var hidden = (MvcHtmlString)null; 
      if (item.Body is MemberExpression) 
      { 
       baseProperty = ((MemberExpression)item.Body).Member.Name; 
       hidden = helper.Hidden(baseProperty, value); 
       attributes.Add("data-value-name", baseProperty); 
      } 
      else 
      { 
       var op = ((UnaryExpression)item.Body).Operand; 
       baseProperty = ((MemberExpression)op).Member.Name; 
       hidden = helper.Hidden(baseProperty, value); 
      } 

      attributes.Add("data-value-id", "service_id"); 

      var automcompleteName = baseProperty + "_autocomplete"; 
      var textBox = (MvcHtmlString)null; 
      if (value != null) 
      { 
       textBox = helper.TextBox(automcompleteName, value, string.Empty, attributes); 
      } 
      else 
      { 
       textBox = helper.TextBox(automcompleteName, null, string.Empty, attributes); 
      } 

      builder.AppendLine(hidden.ToHtmlString()); 
      if (baseProperty == "name") 
      { 
       builder.AppendLine(textBox.ToHtmlString()); 
      } 
     } 

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

回答

0

你可以从这里得到您的确认:

var validation = htmlHelper.ValidationMessageFor(expression, null, new Dictionary<string, object>()); 

UPDATE :

我使用TagBuilder创建标签。我使用tagbuilder做的事情是将验证添加到span或div标记,并让不引人注意的javascript在需要时隐藏/显示它。它返回一个MVCHtmlString,你可以将它添加到你想要显示的元素中

+0

对不起罗伯特,我没有得到它。我已经将该行添加到了构建器中,但是在哪里/如何编写我的消息,以及它将如何显示在客户端? – eyalewin