MVC2 / MVC3 Html Helper or Editor Template solution required

1.3k views Asked by At

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>            
}
2

There are 2 answers

0
AudioBubble On BEST ANSWER

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.

3
Jesse On

If you want to encapsulate the javascript portion you could create an HtmlHelper that will generate the desired content.

An example of what one would look like is as follows:

public static MvcHtmlString DynamicLookupFor(this HtmlHelper htmlHelper, string txtCtrlId, string idCtrlId, string controllerName, string actionName)
{
    // create script tag
    var script = new TagBuilder("script");

    // generate script content
    var result = new StringBuilder();
    result.AppendLine("$(document).ready(function () {");
    result.Append("InitLookup(");

    result.Append("'" + txtCtrlId + "',");
    result.Append("'" + idCtrlId + "',");

    // generate action link
    var url = new UrlHelper(HttpContext.Current.Request.RequestContext);
    result.Append("'" + url.Action(actionName, controllerName));

    result.AppendLine("'});");

    script.InnerHtml = result.ToString();
    return MvcHtmlString.Create(script.ToString());
}

Within your view you can call the helper as follows:

@Html.DynamicLookupFor("#txtDelegatedToLookup", "#Delegated_To_ID", "ContactLookup", "marMIS")

Don't forget to register the helper within the Views folder web.config:

  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="Names Space Of Helper"/>   
  </namespaces>