How to create a generic autocomplete helper for my domain entities in asp.net mvc -


in 1 of asp.net mvc projects, want provide autocomplete general data source url , typed autocomplete domain entities. looking asp.net mvc helper

when started new project in asp.net mvc, had requirement provide input control auto complete many number of domain entities (department, employee, product, categories etc.) , general purpose. wanted use auto completes instead of dropdown list

this useful when there requirement provide auto suggestion kind of data entry end user

two helpers various overloads in terms of having attributes, auto complete type, required, on select call , source url. 1 helper used type view , other 1 view no model binding

how works

helper creates 2 html input elements 1 type of hidden , other type of text. id , name of hidden developer give name of autocomplete or model propertyname. id , name textbox name of hidden _autocomplete (ex: hidden name productid, textbox name productid_auto complete). selected text shown in text box , selected value goes hidden control. on submission of current form both values hidden , text submited server.

if specify source url control, gets data specified url. in other case if specify type of auto complete data loads predefined url.

a javascript callback function can specify execute after select item autocomplete

client side required validation can added using parameter isrequired = true

test requirements •visual studio 2013 •asp.net mvc 5 •jquery-1.10.2 •jquery-ui-1.8.23.custom.min autocomplete plugin

using code

code blocks consists of following resources

•department, employee ( c# classes domain entities of attached source )

•autocompletehelper ( c# statick class define helpers)

•testautocompletecontroller ( c# mvc controller class return data auto completes request)

•customautocomplete script ( jquery script handle auto complete request , responses client)

•view ( index.cshtml design sample view)

first define enum specify type of data load in terms of entity names

autocomplete helper

using system; using system.collections.generic; using system.linq.expressions; using system.text; using system.web.mvc; using system.web.mvc.html;  namespace autocompletehelper_mvc.extensions {      public enum autocompletetype     {         none,         department,         employee,     }      public static class autocompletehelper     {          public static mvchtmlstring autocomplete(this htmlhelper helper, string name, string value, string text, string actionurl, bool? isrequired = false, idictionary<string, object> viewhtmlattributes = null, string onselectfunction = "")         {             return getautocompletestring(helper, name, value, text, autocompletetype.none, actionurl, isrequired, viewhtmlattributes, onselectfunction: onselectfunction);         }         public static mvchtmlstring autocomplete(this htmlhelper helper, string name, string value, string text, autocompletetype autocompletetype, bool? isrequired = false, idictionary<string, object> viewhtmlattributes = null, string onselectfunction = "")         {             return getautocompletestring(helper, name, value, text, autocompletetype, "", isrequired: isrequired, viewhtmlattributes: viewhtmlattributes, onselectfunction: onselectfunction);         }         private static mvchtmlstring getautocompletestring(htmlhelper helper, string name, string value, string text, autocompletetype autocompletetype, string actionurl = "", bool? isrequired = false, idictionary<string, object> viewhtmlattributes = null, string onselectfunction = "")         {             return gethelperstring(helper, name, value, text, autocompletetype, actionurl, isrequired, viewhtmlattributes, onselectfunction);         }         public static mvchtmlstring autocompletefor<tmodel, tvalue>(this htmlhelper<tmodel> helper, expression<func<tmodel, tvalue>> expression, string displayproperty, string actionurl, bool? isrequired = false, idictionary<string, object> viewhtmlattributes = null, string onselectfunction = "")         {             return getautocompleteforstring(helper, expression, displayproperty, autocompletetype.none, actionurl, isrequired, viewhtmlattributes, onselectfunction: onselectfunction);         }         public static mvchtmlstring autocompletefor<tmodel, tvalue>(this htmlhelper<tmodel> helper, expression<func<tmodel, tvalue>> expression, string displayproperty, autocompletetype autocompletetype, bool? isrequired = false, idictionary<string, object> viewhtmlattributes = null, string onselectfunction = "")         {             return getautocompleteforstring(helper, expression, displayproperty, autocompletetype, "", isrequired: isrequired, viewhtmlattributes: viewhtmlattributes, onselectfunction: onselectfunction);         }         private static mvchtmlstring getautocompleteforstring<tmodel, tvalue>(htmlhelper<tmodel> helper, expression<func<tmodel, tvalue>> expression, string displaytext, autocompletetype autocompletetype, string actionurl = "", bool? isrequired = false, idictionary<string, object> viewhtmlattributes = null, string onselectfunction = "")         {             string name = ((memberexpression)expression.body).tostring();             name = name.substring(name.indexof('.') + 1);             func<tmodel, tvalue> method = expression.compile();             object value = null;             if (helper.viewdata.model != null)                 value = method((tmodel)helper.viewdata.model);             return gethelperstring(helper, name, (value != null ? value.tostring() : ""), displaytext, autocompletetype, actionurl, isrequired, viewhtmlattributes, onselectfunction);         }         private static mvchtmlstring gethelperstring(htmlhelper helper, string name, string value, string text, autocompletetype autocompletetype, string actionurl = "", bool? isrequired = false, idictionary<string, object> viewhtmlattributes = null, string onselectfunction = "")         {             if (autocompletetype != autocompletetype.none)             {                 urlhelper url = new urlhelper(helper.viewcontext.requestcontext);                 string acpath = url.content("~/testautocomplete/");                  if (autocompletetype == autocompletetype.department)                     actionurl = acpath + "getdepartments";                 else if (autocompletetype == autocompletetype.employee)                     actionurl = acpath + "getemployees";             }               if (viewhtmlattributes == null)                 viewhtmlattributes = new dictionary<string, object>();              viewhtmlattributes.add("data-autocomplete", true);              viewhtmlattributes.add("data-autocompletetype", autocompletetype.tostring().tolower());              viewhtmlattributes.add("data-sourceurl", actionurl);              if (!string.isnullorempty(onselectfunction))             {                 viewhtmlattributes.add("data-selectfunction", onselectfunction);             }               if (isrequired.hasvalue && isrequired.value)             {                 viewhtmlattributes.add("data-val", "true");                 viewhtmlattributes.add("data-val-required", name + " required");             }              viewhtmlattributes.add("data-valuetarget", name);              mvchtmlstring hidden = helper.hidden(name, value);              mvchtmlstring textbox = helper.textbox(name + "_autocomplete", text, viewhtmlattributes);              var builder = new stringbuilder();              builder.appendline(hidden.tohtmlstring());              builder.appendline(textbox.tohtmlstring());              return new mvchtmlstring(builder.tostring());         }       } } 

department model

using system; using system.collections.generic; using system.linq; using system.web;  namespace autocompletehelper_mvc.models {     public class department     {         public int departmentid { get; set; }         public string departmentname { get; set; }         public static list<department> totaldepartments         {                         {                 return new list<department>{                                             new department{departmentid=1,departmentname="accounts"},                                             new department{departmentid=2,departmentname="advertisement"},                                             new department{departmentid=3,departmentname="sales"},                                             new department{departmentid=4,departmentname="shipment"},                                             new department{departmentid=5,departmentname="production"},                                             new department{departmentid=6,departmentname="marketing"}                                             };             }         }         public static list<department> getdepartmentslikename(string namestring)         {             var x=totaldepartments.where<department>(d=>d.departmentname.tolower().startswith(namestring.tolower()));             return x.tolist();          }     } } 

employee model

using system; using system.collections.generic; using system.componentmodel.dataannotations; using system.linq; using system.web;  namespace autocompletehelper_mvc.models {     public class employee     {         public int employeeid { get; set; }         [required]         public string employeename { get; set; }         public static list<employee> totalemployees         {                         {                 return new list<employee>{                                             new employee{employeeid=1,employeename="addison",departmentid=1},                                             new employee{employeeid=2,employeename="ashwin",departmentid=1},                                             new employee{employeeid=3,employeename="alden",departmentid=1},                                             new employee{employeeid=4,employeename="anthony",departmentid=6},                                             new employee{employeeid=5,employeename="bailee",departmentid=5},                                             new employee{employeeid=6,employeename="baileigh",departmentid=4},                                             new employee{employeeid=7,employeename="banjamin",departmentid=2},                                             new employee{employeeid=8,employeename="cadan",departmentid=3},                                             new employee{employeeid=9,employeename="cadimhe",departmentid=2},                                             new employee{employeeid=10,employeename="carissa",departmentid=1},                                             new employee{employeeid=11,employeename="ceara",departmentid=2},                                             new employee{employeeid=12,employeename="cecilia",departmentid=1}                                             };             }         }         public int departmentid { get; set; }          public static list<employee> getemployeeslikename(string namestring)         {             var x = totalemployees.where<employee>(d => d.employeename.tolower().startswith(namestring.tolower()));             return x.tolist();          }     } } 

test controller

using autocompletehelper_mvc.models; using system; using system.collections.generic; using system.linq; using system.web; using system.web.mvc;  namespace autocompletehelper_mvc.controllers {      public class testautocompletecontroller : controller     {         //         // get: /autocomplete/         public actionresult index()         {             var empobj = new employee { employeeid = 1, employeename = "michale" };             return view(empobj);         }          public actionresult getemployees(string searchhint)         {             return json(employee.getemployeeslikename(searchhint),jsonrequestbehavior.allowget);         }         // get: /autocomplete/         public actionresult getdepartments(string searchhint)         {             return json(department.getdepartmentslikename(searchhint), jsonrequestbehavior.allowget);         }         // get: /autocomplete/         public actionresult getgeneralitems(string searchhint)         {             return json(employee.getemployeeslikename(searchhint), jsonrequestbehavior.allowget);         }     } } 

custom autocomplete javascript

//attached autocomplete widget autocomplete controls $(document).ready(function () {     bindautocomplete(); }); function bindautocomplete() {      $('[data-autocomplete]').each(function (index, element) {         var sourceurl = $(element).attr('data-sourceurl');         var autocompletetype = $(element).attr('data-autocompletetype');         $(element).autocomplete({             source: function (request, response) {                 $.ajax({                     url: sourceurl,                     datatype: "json",                     data: { searchhint: request.term },                     success: function (data) {                         response($.map(data, function (item) {                             if (autocompletetype == 'none') {                                 return {                                     label: item.employeename,                                     value: item.employeename,                                     selectedvalue: item.employeeid                                 };                             }                             else if (autocompletetype == 'department') {                                 return {                                     label: item.departmentname,                                     value: item.departmentname,                                     selectedvalue: item.departmentid                                  };//                             }                             else if (autocompletetype == 'employee') {                                 return {                                     label: item.employeename,                                     value: item.employeename,                                     selectedvalue: item.employeeid                                  };//                             }                         }));                     },                     error: function (data) {                         alert(data);                     },                 });             },             select: function (event, ui) {                 var valuetarget = $(this).attr('data-valuetarget');                 $("input:hidden[name='" + valuetarget + "']").val(ui.item.selectedvalue);                  var selectfunc = $(this).attr('data-selectfunction');                 if (selectfunc != null && selectfunc.length > 0) {                     window[selectfunc](event, ui);                 }             },             change: function (event, ui) {                 var valuetarget = $(this).attr('data-valuetarget');                 $("input:hidden[name='" + valuetarget + "']").val('');             },         });     }); } 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -