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>
}
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...
...and requires a using statement at the top of the razor view page...
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.
The controller method on the server...
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.