Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8002137
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T16:16:27+00:00 2026-06-04T16:16:27+00:00

I have a jquery based bespoke lookup control that works well, but I wish

  • 0

I have a jquery based bespoke lookup control that works well, but I wish to encapsulate it into a neater solution. The below is the code included in the Razor view. Behind the scenes there is also a bespoke jquery function called ‘InitLookup’ that does the majority of the work at runtime.

   <script type="text/javascript">
       $(document).ready(function () {
           InitLookup('#txtDelegatedToLookup', '#Delegated_To_ID', '@Url.Action("ContactLookup", "marMIS")');
       });
   </script>
   @Html.HiddenFor(m => m.Delegated_To_ID)
   <input id="txtDelegatedToLookup" type="text" />

Ideally, I would like to whittle this down to a neater and more re-usable solution, where the javascript InitLookup() is dynamically created and encapsulated within, possibly as below…

@Html.DynamicLookupFor(m => m.Delegated_To_ID, "ContactLookup", "marMIS")

…where “marMIS” is the controller, and “ContactLookup” is a controller method. These being the address to use to get the data during a lookup.

I tried to create an Editor Template called DynamicLookup in the /Views/Shared/EditorTemplates folder, but the wasn’t recognised when using @Html.DynamicLookup(…

Any takers on this one? Cheers!

———— App_Code suggestion below! Addendum to original question! ————————-

OK, so I have copied my code into a new App_Code folder file called CustomHelpers.cshtml. How do I pass the lambda expression into here and then use it?

@using System.Security.Policy
@using System.Web.Mvc.Html

@helper DynamicLookup(LAMBDAEXPR, CtrlId, Controller, Method) {
    @Html.HiddenFor(LAMBDAEXPR)
    <input id="txtDelegatedToLookup" type="text" />
    @Html.ValidationMessageFor(LAMBDAEXPR)  

    <script type="text/javascript">
        $(document).ready(function () {
            InitLookup(txtCtrlId, idCtrlId, '@Url.Action(Controller, Method)');
        });
    </script>            
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T16:16:28+00:00Added an answer on June 4, 2026 at 4:16 pm

    OK, here’s what I ended up doing in the end. It works very very well indeed! It will need a little polish in the future, and it leaves the door open to extend this a little too. For example, the control validates, but it doesn’t color itself as per the rest of my validation, rather it just shows the textual validation message.

    The functionality is called as such…

    @Html.CustomLookupFor(m => m.Task_History.Delegated_To_ID, "txtDelegatedToLookup", @Url.Action("ContactLookup", "marMIS"), new { width = "250px" })
    

    …and requires a using statement at the top of the razor view page…

    @using Custom.MVC.Helpers;
    

    BTW, two things…
    jquery 1.7.2+ and jquery ui 1.8.16+ is what was used whilst I was developing this!
    Also, the functionality in the first code section below includes both a minified version of the
    javascript functionality within the code, and also a commented section containing the original
    javascript code formatted nicely.

    There are then two peices of code in the background. The first one here is the re-usable code that I was seeking to develop with regards to my initial question. The second one below it is the controller method on the server.

    using System;
    using System.Linq.Expressions;
    using System.Text;
    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    using System.Web.Routing;
    
    namespace Custom.MVC.Helpers
    {
        public static class CustomHtmlHelperExtensions
        {
            public static MvcHtmlString CustomLookupFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> exp, string id, string url, object options)
            {   
                var hidCtrlId = id + "_id"; 
    
                //Options
                var opt = new RouteValueDictionary(options);
                var textBoxWidth = (opt["width"] != null) ? opt["width"].ToString() : "";
                var textBoxVisibility = (opt["visibility"] != null) ? opt["visibility"].ToString() : ""; 
    
                //Construct the script fired when the document is fully loaded
                var sbScript = new StringBuilder();
                sbScript.Append("<script type='text/javascript'>");
                sbScript.Append("  function InitDynamicLookupFor(e,f){var g='#'+e;var h='#'+e+'_id';$(g).click(function(){$(g).val('');$(h).val('');$(h).trigger('change')});$(g).autocomplete({minLength:3,delay:100,autoFocus:true,autofill:true,mustMatch:true,matchContains:true,width:220,source:function(c,d){$.ajax({url:f,type:'POST',dataType:'json',data:{searchId:0,searchTerm:c.term,searchLimit:10},success:function(b){d($.map(b,function(a){return{id:a.id,value:a.value}}))}})},create:function(b,c){if($(h).val()!=''){$.ajax({url:f,type:'POST',dataType:'json',data:{searchId:$(h).val(),searchTerm:'',searchLimit:1},success:function(a){$(g).val(a[0].value);$(g).removeClass('DynamicLookupForNotSelected');$(g).addClass('DynamicLookupForSelected')}})}},select:function(a,b){$(h).val(b.item.id);$(g).val(b.item.value);$(g).removeClass('DynamicLookupForNotSelected');$(g).addClass('DynamicLookupForSelected');$(h).trigger('change');return false},open:function(a,b){$(h).val(null);$(g).removeClass('DynamicLookupForSelected');$(g).addClass('DynamicLookupForNotSelected')}});if($(h).val()==''){$(g).val('Type here to search!');$(g).removeClass('DynamicLookupForSelected');$(g).addClass('DynamicLookupForNotSelected')}}");
                sbScript.Append("  ");
                sbScript.Append("  $(document).ready(function () {");
                sbScript.Append("    InitDynamicLookupFor('" + id + "', '" + url + "');");
                sbScript.Append("  });");
                sbScript.Append("</script>");
    
                //Construct the HTML controls for the DynamicLookup and its validation
                var sbCtrls = new StringBuilder();
                sbCtrls.Append(html.HiddenFor(exp, new { id=hidCtrlId }));
                sbCtrls.Append("<input id='" + id + "' type='text' style='width:" + textBoxWidth + "; visibility:" + textBoxVisibility + ";' />");
                sbCtrls.Append(html.ValidationMessageFor(exp));
    
                //Return the lot back to the interface
                var retString = sbScript.ToString() + sbCtrls.ToString();
                return new MvcHtmlString(retString);
            }
    
        }
    }
    
                //*** This is the original javascript code before it is minified for use above!  DON'T DELETE! ***
                //
                //    function InitDynamicLookupFor(textBox, url) {
                //    var $textBox = '#' + textBox;
                //    var $hiddenId = '#' + textBox + '_id';
    
                //    $($textBox).click(function () {
                //        $($textBox).val('');
                //        $($hiddenId).val('');
                //        $($hiddenId).trigger('change');
                //    });
    
                //    $($textBox).autocomplete({
                //        minLength: 3,
                //        delay: 100,
                //        autoFocus: true,
                //        autofill: true,
                //        mustMatch: true,
                //        matchContains: true,
                //        width: 220,
                //        source: function (request, response) {
                //            $.ajax({
                //                url: url, type: 'POST', dataType: 'json',
                //                data: { searchId: 0, searchTerm: request.term, searchLimit: 10 },
                //                success: function (data) {
                //                    response($.map(data, function (item) {
                //                        return {
                //                            id: item.id,
                //                            value: item.value
                //                        };
                //                    }));
                //                }
                //            });
                //        },
                //        create: function (event, ui) {
                //            if ($($hiddenId).val() != '') {
                //                $.ajax({
                //                    url: url, type: 'POST', dataType: 'json',
                //                    data: { searchId: $($hiddenId).val(), searchTerm: '', searchLimit: 1 },
                //                    success: function (data) {
                //                        $($textBox).val(data[0].value);
                //                        $($textBox).removeClass('DynamicLookupForNotSelected');
                //                        $($textBox).addClass('DynamicLookupForSelected');
                //                    }
                //                });
                //            }
                //        },
                //        select: function (event, ui) {
                //            $($hiddenId).val(ui.item.id);
                //            $($textBox).val(ui.item.value);
                //            $($textBox).removeClass('DynamicLookupForNotSelected');
                //            $($textBox).addClass('DynamicLookupForSelected');
                //            $($hiddenId).trigger('change');
                //            return false;
                //        },
                //        open: function (event, ui) {
                //            $($hiddenId).val(null);
                //            $($textBox).removeClass('DynamicLookupForSelected');
                //            $($textBox).addClass('DynamicLookupForNotSelected');
                //        }
                //    });
    
                //    //If no value selected by now, indicate to the user how to use the control
                //    if ($($hiddenId).val() == '') {
                //        $($textBox).val('Type here to search!');
                //        $($textBox).removeClass('DynamicLookupForSelected');
                //        $($textBox).addClass('DynamicLookupForNotSelected');
                //    }
                //}
    

    The controller method on the server…

    public JsonResult ContactLookup(int searchId, string searchTerm, int searchLimit)
        {
            //Prepare search filter from criteria entered
            var p = PredicateBuilder.True<vw_Contact_Verbose>();
            if (searchId != 0) p = p.And(x => x.Contact_ID == searchId); 
            if (searchTerm != "") p = p.And(x => x.Fullname.Contains(searchTerm));
    
            //Grab data
            var results =
                (from x in _mDb.ent.vw_Contact_Verbose.AsExpandable().Where(p).OrderBy("Fullname Desc").Take(searchLimit)
                 select new { id = x.Contact_ID, value = x.Fullname + " (" + x.Company + ")" }).ToArray();
    
            return Json(results, JsonRequestBehavior.AllowGet);
        }  
    

    I do hope that this re-useable code is found to be as useful to anybody else as it is to me. It’s certainly made my code less verbose in razor views.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a jQuery based accordion style navigation that I am trying to modify.
I have autocomplete text box, that is JQuery based. when i record the macro,
Drupal has a very well-architected, jQuery -based autocomplete.js . Usually, you don't have to
I'd simply like not to have a JQuery based HTML editor that use <b>
I'm in search for a jQuery-based Date/Time Selector. I have found a few that
I have a small jQuery based script for animating the border on images that
I have a simple javascript (JQuery based) method that does some css magic to
I am trying to create a Javascript/Jquery based application that will eventually go into
peace folks, I have this small piece of jquery based code, that grabs all
I have setup a jquery based marquee, This works perfectly fine until I have

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.