English 中文(简体)
MVC2/MVC3 Html Html 帮助或编辑者模板解决方案
原标题:MVC2 / MVC3 Html Helper or Editor Template solution required

我有一个基于简洁的外观控制器,它运作良好,但我希望把它包成一个更干净的解决方案。下面是Razor 视图中包含的代码。在幕后还有一个叫做InitLookup的可口的拼图功能,在运行时完成大部分工作。

   <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" />

最理想的情况是,我想把这个写进一个更干净、更便于再使用的解决方案, 在那里,标本的InitLookup()是动态的, 并封装在其中, 可能如下:...

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

...“ MAMIS” 是控制器, 而“ 联系人监视” 是一种控制器方法。 这些是用来在调查中获取数据的地址 。

我试图在/Option/Shared/EditorTemplates 文件夹中创建一个名为“动态图”的编辑器模板,但使用 )时无法识别

有收买者吗 干杯

- App_Code建议下面!

OK, 所以我已经将我的代码复制为一个新的 App_ Code 文件夹文件, 名为 CustomelpHelps. cshtml 。 我如何将 ambda 表达方式传送到这里然后使用?

@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,这就是我最后所做的。它确实非常有效!它在未来需要一点抛光剂,它也敞开了门来扩展它。例如,控制验证,但它与我的其他验证结果不同,它只是显示文本验证信息。

这个功能被称为这样...

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

...并要求在剃须刀视图页面的顶部 使用语句...

@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.

然后背景中有两种代码。 第一个是我要针对我最初的问题开发的可重复使用的代码。 下面的第二个是服务器上的控制器方法 。

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);
    }  

我希望这个可重复使用的代码能对我和其他人一样有用。 它肯定使我的代码在剃须刀的视角中变得不那么动人。

问题回答

如果您想要封装 javascript 部分, 您可以创建一个 < code> HtmlHelper < /code >, 生成想要的内容 。

其外观的一个例子如下:

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());
}

在您看来,您可拨打以下求助电话:

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

不要忘记在视图文件夹 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>




相关问题
How to update shared view adminheader.cshtml from a model

I ve added a drop down into my shared adminheader.cshtl view and it needs to be dynamically updated from data from a table. So when I use another view like routeplan.cshtml I load the view from ...

ASP.NET MVC Razor view engine

After reading Scott Guthrie s blog entry about the new Razor view engine for ASP.NET MVC and reading this question comparing the available view engines. Razor seems to address most of the problems ...

Client Id for Property (ASP.Net MVC)

I m trying to do a label for a TextBox in my View and I d like to know, how can I take a Id that will be render in client to generate scripts... for example: <label for="<%=x.Name.ClientId%>"...

Get Current Area Name in View or Controller

How do you get the current area name in the view or controller? Is there anything like ViewContext.RouteData.Values["controller"] for areas?

MVC which submit button has been pressed

I have two buttons on my MVC form: <input name="submit" type="submit" id="submit" value="Save" /> <input name="process" type="submit" id="process" value="Process" /> From my Controller ...

热门标签