Skip to content

Instantly share code, notes, and snippets.

@andreabalducci
Created October 5, 2010 08:26
Show Gist options
  • Save andreabalducci/611222 to your computer and use it in GitHub Desktop.
Save andreabalducci/611222 to your computer and use it in GitHub Desktop.
<div class="field-row">
<div class="field-box">
<%=Html.AutoCompleteFor(
x => x.Customer.CompanyName,
x => x.Customer.Id,
Url.Action("Autocomplete", "Customer")
) %><br />
</div>
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Demo.WebSite.Extensions
{
public static class HtmlExtensions
{
private static object readonlyAttribs = new { disabled = true };
static HtmlExtensions()
{
}
public static MvcHtmlString ReadonlyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return htmlHelper.TextBoxFor(expression, readonlyAttribs);
}
public static MvcHtmlString ReadonlyTextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return htmlHelper.TextAreaFor(expression, readonlyAttribs);
}
public static MvcHtmlString DatePickerFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return htmlHelper.EditorFor(expression);
}
public static MvcHtmlString AutoCompleteFor<TModel, TDisplayProperty, TKeyProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TDisplayProperty>> displayField, Expression<Func<TModel, TKeyProperty>> keyField, string url)
{
string displayFieldName = HtmlHelper.GenerateIdFromName(ExpressionHelper.GetExpressionText(displayField));
string keyFieldName = HtmlHelper.GenerateIdFromName(ExpressionHelper.GetExpressionText(keyField));
StringBuilder sb = new StringBuilder();
sb.Append(htmlHelper.EditorFor(displayField));
sb.Append(htmlHelper.HiddenFor(keyField));
sb.AppendLine();
sb.AppendLine("<script type=\"text/javascript\">");
sb.AppendLine("$(function(){");
sb.AppendLine("$('#" + displayFieldName + "').autocomplete({");
sb.AppendLine("source: function(request, response){");
sb.AppendLine("$.getJSON('"+url+"', request, response);");
sb.AppendLine("}");
sb.AppendLine(",minLength: 1");
sb.AppendLine(",select: function(event, ui) {");
sb.AppendLine("$('#" + keyFieldName + "').val(ui.item ? ui.item.id : '');");
sb.AppendLine("}");
sb.AppendLine("});");
sb.AppendLine("});");
sb.AppendLine("</script>");
return MvcHtmlString.Create(sb.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment