好的,这就是我最终做的事情。它确实非常好用!将来它需要一点点润色,它也为扩展它敞开了大门。例如,控件进行了验证,但它不会按照我的其余验证为自己着色,而只是显示文本验证消息。
该功能被称为...
@Html.CustomLookupFor(m => m.Task_History.Delegated_To_ID, "txtDelegatedToLookup", @Url.Action("ContactLookup", "marMIS"), new { width = "250px" })
...并且需要在剃刀视图页面顶部使用 using 语句...
@using Custom.MVC.Helpers;
顺便说一句,有两件事...... jquery 1.7.2+ 和 jquery ui 1.8.16+ 是我开发这个时使用的!此外,下面第一个代码部分中的功能包括代码中 javascript 功能的缩小版本,以及包含格式良好的原始 javascript 代码的注释部分。
然后在后台有两段代码。这里的第一个是关于我最初的问题我正在寻求开发的可重用代码。它下面的第二个是服务器上的控制器方法。
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');
// }
//}
服务器上的控制器方法...
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);
}
我确实希望发现这个可重用的代码对其他人和我一样有用。这肯定使我的代码在剃刀视图中不那么冗长。