AutoCompleteExtensions.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web.Mvc;
  6. using System.Linq.Expressions;
  7. namespace Bowin.Web.Controls.Mvc
  8. {
  9. public static class AutoCompleteExtensions
  10. {
  11. public static MvcHtmlString AutoComplete(this HtmlHelper htmlHelper,
  12. AutoCompleteOptions autoCompleteOptions,
  13. System.Collections.Generic.IDictionary<string, string> htmlAttributes = null)
  14. {
  15. if (!string.IsNullOrEmpty(autoCompleteOptions.Url))
  16. {
  17. var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
  18. autoCompleteOptions.Url = urlHelper.Content(autoCompleteOptions.Url);
  19. }
  20. return MvcHtmlString.Create(Bowin.Web.Controls.Mvc.AutoComplete.CreateControl(autoCompleteOptions, htmlAttributes).Render());
  21. }
  22. public static MvcHtmlString AutoComplete<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
  23. Expression<Func<TModel, TProperty>> expression,
  24. AutoCompleteOptions autoCompleteOptions,
  25. System.Collections.Generic.IDictionary<string, string> htmlAttributes = null)
  26. {
  27. if (expression == null)
  28. {
  29. throw new ArgumentNullException("expression");
  30. }
  31. ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
  32. //获取值
  33. //modelMetadata.Model
  34. //获取字段名称,对应标签的name
  35. string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
  36. autoCompleteOptions.Name = fullHtmlFieldName;
  37. if (modelMetadata.Model != null)
  38. {
  39. autoCompleteOptions.DefaultValue = modelMetadata.Model;
  40. }
  41. if (!string.IsNullOrEmpty(autoCompleteOptions.Url))
  42. {
  43. var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
  44. autoCompleteOptions.Url = urlHelper.Content(autoCompleteOptions.Url);
  45. }
  46. return MvcHtmlString.Create(Bowin.Web.Controls.Mvc.AutoComplete.CreateControl(autoCompleteOptions, htmlAttributes).Render());
  47. }
  48. }
  49. }