如何从Html Helper Class的脚本函数调用Java脚本函数?

时间:2016-01-06 11:26:04

标签: javascript asp.net-mvc razor jqgrid html-helper

我有一个剃刀视图,其中有一个名为getDocumentDetails的函数。我已经编写了一个跟随

的html助手类
     public static MvcHtmlString CreateJQGrid<T>(this HtmlHelper helper, GridViewModel<T> model)
    {
        bool blnEditIcon = false;
        bool blnEditRights = false;
        var htmlBuilder = new StringBuilder();

        // Place the Upload Button.
        if ((!string.IsNullOrEmpty(model.UploadAction) || !string.IsNullOrEmpty(model.AddNewAction)) && model.UserAccessRights != Constants.UserType.View)
        {
            htmlBuilder.AppendFormat(@"<div align='right' class='icon-list'>");
            if (!string.IsNullOrEmpty(model.UploadAction) && model.UserAccessRights != Constants.UserType.Checker && model.UploadRights == true)
            {
                htmlBuilder.AppendFormat(@"<a class=""upload"" href=""{0}"" id=""Upload"">Upload &nbsp;&nbsp; </a>", model.UploadAction);
            }
            // Place the Add New Button
            if (!string.IsNullOrEmpty(model.AddNewAction) && model.UserAccessRights != Constants.UserType.Checker)
            {
                htmlBuilder.AppendFormat(@"<a class=""addnew"" href=""{0}"" id=""AddNew"">Add New</a>", model.AddNewAction);
            }
            htmlBuilder.AppendFormat(@" </div><br /><br />");
        }
        htmlBuilder.AppendFormat(@"<div align='right' class='icon-list'>");

        if (!model.BulkApprovalRights)
            model.multiselectCheckBox = false;

        htmlBuilder.AppendFormat(@"</div>");


        htmlBuilder.AppendFormat(@"<table id=""{0}"" class=""scroll"" cellpadding=""0"" cellspacing=""0""></table>", model.Id);
        htmlBuilder.AppendFormat(@"<div id=""{0}Pager"" class=""scroll"" style=""text-align:center;""></div>", model.Id);

        htmlBuilder.AppendFormat(@"<script type=""text/javascript"">");

        htmlBuilder.AppendFormat(@" function EditingValidation(id) {{
                                           var selr = $('#{0}').jqGrid('getGridParam','selrow'); 
                                           var rowData = $('#{0}').getRowData(selr);
                                            if(rowData.Edit=='') 
                                            {{
                                                alert('You cannot edit the     selected record.'); return [false, ''];
                                            }}
                                          return [true, ''];                                       
   Rejected
                                }}", model.Id);
        //Md Aslam
        htmlBuilder.AppendFormat(@" function addLinkk(cellvalue, options,          
   rowObject) {{
                                          alert('AddLinkk');
                                return  '<a href=""#""  onclick=GridCellClick(""'+cellvalue+'"")><font color=""blue""><u>'+cellvalue+'</u></font></a>';

                                }}", model.Id);

        htmlBuilder.AppendFormat(@" function GridCellClick(cellValue) {{

                                        getDocumentDetails(); }}", model.Id);


        htmlBuilder.AppendFormat(@"function highlight (cellValue, options, 
  rowObject) {{ 
            if(cellValue=='Approved')               
                return '<span class=""label-
successforecolor"">'+cellValue+'</span>';
            else if(cellValue=='Rejected')               
                           return '<span class=""label-
  dangerforecolor"">'+cellValue+'</span>';
            else if(cellValue=='Pending')               
                           return '<span class=""label-infoforecolor"">'+cellValue+'</span>';
            else
                return cellValue;
                        }}");

        htmlBuilder.AppendFormat(@"$(function()");
        htmlBuilder.AppendFormat(@"{{");
        htmlBuilder.AppendFormat(@"var lastsel;");
        htmlBuilder.AppendFormat(@"$('#{0}').jqGrid({{", model.Id);
        htmlBuilder.AppendFormat(@"url: '{0}',", WebExtensions.GetUrlContent() + model.Url);
        //htmlBuilder.AppendFormat(@"editurl: '/InwardOutward/Edit',");
        if (!string.IsNullOrEmpty(model.EditUrl))
            htmlBuilder.AppendFormat(@"editurl: '{0}',", WebExtensions.GetUrlContent() + model.EditUrl);
        htmlBuilder.AppendFormat(@"datatype: 'json',");
        htmlBuilder.AppendFormat(@"mtype: 'POST',height:280,");
        //Create Columns Names
        htmlBuilder.AppendFormat(@"colNames: [");
        foreach (var action in model.Actions)
        {
            htmlBuilder.AppendFormat(@"'{0}',", action.Name.ToString());
        }
        foreach (var column in model.Columns)
        {
            htmlBuilder.AppendFormat(@"'{0}',", column.Name.ToString());
        }
        htmlBuilder.AppendFormat(@"],");

        //Create Columns
        htmlBuilder.AppendFormat(@"colModel: [");

        foreach (var column in model.Columns.OrderBy(x => x.ActionOrder))
        {
            if (column.Name.ToUpper() == "REMARKS")
            {
                htmlBuilder.AppendFormat(@"{{name: '{0}', 
                                        index: '{1}', 
                                        align: '{2}', 
                                        search: {3},                                            
                                        sortable: {4},
                                        width: {5},                                             
                                        hidden: {6},
                                        sorttype: '{7}',
                                        sortable: true,
                                        searchoptions: {{sopt:[{8}]}},
                                        editable: {9},
                                        hidedlg: {10},
                                        edittype:'{11}',                                          
                                        editrules: {{custom: true, custom_func: EditingValidation}},
                                        classes: 'textInDiv',
                                        formatter: function (v) {{return '<div>' + $.jgrid.htmlEncode(v) + '</div>';}}
                        ", column.Index.ToString()
                      , column.Index
                      , column.Align == null ? "left" : column.Align.ToLower()
                      , column.IsSearch.ToString().ToLower()
                      , column.IsSortable.ToString().ToLower()
                      , column.Width > 0 ? column.Width : 100
                      , column.IsHidden.ToString().ToLower()
                      , column.SortType == null ? "string" : column.SortType.ToString().ToLower()
                      , column.SearchOptions == null ? "'eq','bw','bn','cn','nc','ew','en'" : column.SearchOptions.ToString().ToLower()
                      , column.IsEditable.ToString().ToLower()
                      , column.IsEditHidden.ToString().ToLower()
                      , column.IsEditTypeSelect == true ? "select" : "text"
                      );
            }
            else
            {
                htmlBuilder.AppendFormat(@"{{name: '{0}', 
                                        index: '{1}', 
                                        align: '{2}', 
                                        search: {3},                                            
                                        sortable: {4},
                                        width: {5},                                             
                                        hidden: {6},
                                        sorttype: '{7}',
                                        sortable: true,
                                        searchoptions: {{sopt:[{8}]}},
                                        editable: {9},
                                        hidedlg: {10},
                                        edittype:'{11}',                                          
                                        editrules: {{custom: true, 
   custom_func: EditingValidation}}"
                   , column.Index.ToString()
                   , column.Index
                   , column.Align == null ? "left" : column.Align.ToLower()
                   , column.IsSearch.ToString().ToLower()
                   , column.IsSortable.ToString().ToLower()
                   , column.Width > 0 ? column.Width : 100
                   , column.IsHidden.ToString().ToLower()
                   , column.SortType == null ? "string" : 
 column.SortType.ToString().ToLower()

                   , column.SearchOptions == null ? 
     "'eq','bw','bn','cn','nc','ew','en'" : 
      column.SearchOptions.ToString().ToLower()
                   , column.IsEditable.ToString().ToLower()
                   , column.IsEditHidden.ToString().ToLower()
                   , column.IsEditTypeSelect == true ? "select" : "text"
                   );
            }
            if (column.Index == "Status")
                htmlBuilder.AppendFormat(@",formatter:highlight
                                            }},");
            else
                htmlBuilder.AppendFormat(@"}},");
            if (column.IsEditable && !blnEditRights && 
  !string.IsNullOrEmpty(model.EditUrl))
                blnEditIcon = true;
        }
        htmlBuilder.AppendFormat(@"],");

        htmlBuilder.AppendFormat(@"loadtext: 'Loading {0}',", 
 model.Caption);
        htmlBuilder.AppendFormat(@"pager: jQuery('#{0}Pager'),", model.Id);
        htmlBuilder.AppendFormat(@" rowNum: 20,
                                    rowList: [10, 20, 30, 40, 50, 60, 70, 
  80, 90, 100, 200,500,1000,100000000],  
                                    loadonce: true,                                          
                                    ignoreCase: true,
                                    viewrecords: true,                                        
                                        ");

        //htmlBuilder.AppendFormat(@"multiSort: true,");                                   


        htmlBuilder.AppendFormat(@"caption: '{0}',", model.Caption);


        htmlBuilder.AppendFormat(@"pagepos: 'left',
                                   forceFit: true,
                                   autowidth: true,
                                   shrinkToFit: false,");
        htmlBuilder.AppendFormat(@"}});");

        htmlBuilder.AppendLine(@"");
        htmlBuilder.AppendLine(@"");
        htmlBuilder.AppendFormat(@"$('#{0}').jqGrid(", model.Id);
        htmlBuilder.AppendFormat(@"'navGrid', '#{0}Pager',{{ search: true, 
   add: false, edit: true, del: false, refresh: false, searchtext: 
  'Search',edittext: 'Edit',position: 'left'                                            
                                        ,", model.Id);

        if (blnEditIcon)
        {
            htmlBuilder.AppendFormat(@"edit: true, edittext: 'Edit'");
            //afterSubmit:function(response, postdata){{ alert('Coming');       
  var json   = response.responseText;var result = JSON.parse(json);return 
  [result.status,result.message,null];    }}
        }
        else
        {
            htmlBuilder.AppendFormat(@"edit: false,");
        }

        htmlBuilder.AppendFormat(@"
                                    }},");

        htmlBuilder.AppendFormat(@" {{ 
 afterSubmit:function(response, postdata){{  

 if(response.status == 200)
{{ 
$('.topinfo').html('<div   
          style=\'color:red\'>'+response.responseText+'</div>');

 var tinfoel = $('.tinfo').show();
  //tinfoel.delay(1500).fadeOut();
  return [true,''];
 }} else {{
  return [false,'error message'];
 }}
  }},
 onclickPgButtons:function(){{
 $('.topinfo').html('<div style=\'color:green\'> &nbsp;&nbsp;&nbsp;</div>');
}}

 }},
                                     {{}},
                                     {{}},
                                    {{multipleSearch:true,  
   multipleGroup:true, showQuery: true,closeAfterSearch: true,searchOnEnter:          
    true}}");
        htmlBuilder.AppendFormat(@");");

        /* Add this line to include a separator between buttons */
        SeparatorBetweenButtons(model.Id, htmlBuilder);

        //Enable the Refresh
        htmlBuilder.AppendLine(@"");
        htmlBuilder.AppendLine(@"");
        htmlBuilder.AppendFormat(@"$('#{0}').jqGrid('navButtonAdd', '#{1}Pager', {{", model.Id, model.Id);
        htmlBuilder.AppendFormat(@"caption: 'Refresh',");
        htmlBuilder.AppendFormat(@"buttonicon: 'ui-icon-refresh',
                                    title: 'Refresh',");
        htmlBuilder.AppendFormat(@"onClickButton: function () {{");
        htmlBuilder.AppendFormat(@"$('#{0}').setGridParam({{ datatype:      
     'json' }});", model.Id);

        htmlBuilder.AppendFormat(@"$('#{0}')[0].clearToolbar();", model.Id);
        htmlBuilder.AppendFormat(@"$('#{0}').trigger('reloadGrid');", 
    model.Id);
        htmlBuilder.AppendFormat(@"}}");
        htmlBuilder.AppendFormat(@"}});");

        SeparatorBetweenButtons(model.Id, htmlBuilder);
        htmlBuilder.AppendLine(@"");
        htmlBuilder.AppendLine(@"");
        htmlBuilder.AppendFormat(@"$('#{0}').jqGrid('filterToolbar', {{ 
 searchOperators: true, defaultSearch:'cn' }});", model.Id);

        htmlBuilder.AppendFormat(@"  }}); ");
        htmlBuilder.AppendFormat(@"</script>");

        return MvcHtmlString.Create(htmlBuilder.ToString());

    }

其中Edit列包含jqgrid formatter属性,并调用addLinkk函数。在那个addLinkk函数中,称为getDocumentDetails函数,它在实际的剃刀视图文件中,这就是剃刀文件。在调用getDocumentDetails时,它显示&#34; getDocumentDetails未定义&#34;。

这里的问题是我无法从html助手类调用该函数。我不知道该怎么做。请有人帮助我。

我的剃刀观点如下。

  @using Intranet.Common;
   @using CSR.UI.Web.Helpers;
   @using CSR.Model;
  @using Intranet.Utilities;
 @model CorpGroupModel
 @{

  ViewBag.Title = "AddEditCorpGroup";
//Layout = "~/Views/Shared/_Layout.cshtml";
 }

 <div class="panel panel-default">
<div class="panel-heading">
    <h3 class="panel-title">
        Manage Corporate Group </h3>
</div>
<div class="panel-body">

    <br />
    @Html.CreateJQGrid(Model.GridData)
</div>
   </div>

   <br/>

<div class="panel panel-default">
   <div class="panel-heading">
      <h3 class="panel-title">
          Add / Edit Corporate Group</h3>
   </div>
   <div class="panel-body">
    <div class="icon-list">
        @Html.ActionLink("Back to List", "ManageCorpGroup", null, new { @id     
   = "BackToList", @class = "backbtn" })
    </div>
    </br>
        @using (Html.BeginForm(Constants.Action.AddEditCorpGroup,       
   Constants.Controller.CorpGroup, FormMethod.Post, new { @role = "form" }))
    {

        @Html.AntiForgeryToken()          
        @Html.HiddenFor(m => m.IsAdd)
        @Html.HiddenFor(m => m.Id)
        @Html.HiddenFor(m => m.CompanyId);
        @Html.HiddenFor(m => m.Status);         
        @Html.HiddenFor(m => m.CreateUser);                                              
        @Html.HiddenFor(m => m.CreateDate);
        @Html.HiddenFor(m => m.IsUserLoggedIn);
        @Html.HiddenFor(m => m.LoggedInUserSeq);
        @Html.HiddenFor(m => m.UserAccessRights); 
        @Html.HiddenFor(m => m.IsMakerRemarks)
        @Html.HiddenFor(m => m.IsCheckerRemarks) 

        <div class="row">
            <div class="col-md-4">
                <label for="" class="control-label">
                    Corporate Group Name </label><br />
                @Html.TextBoxFor(model => model.CorpGroupName, new { @class 
   = "form-control mand", @onkeypress = "return OnlyAlphaNumeric(this);", 
 @onkeyup = "return CPOnlyAlphaNumeric(this);" }).DisableIf(() => 
  Model.IsReadOnly == true)
            </div>
             <div class="col-md-4">
                <label for="" class="control-label">
                    Corporate Group Name </label><br />
                @Html.TextBoxFor(model => model.ManagingDirector, new { 
  @class = "form-control mand", @onkeypress = "return 
 OnlyAlphaNumeric(this);", @onkeyup = "return CPOnlyAlphaNumeric(this);" 
 }).DisableIf(() => Model.IsReadOnly == true)

            </div>
             <div class="col-md-4">
                <label for="" class="control-label">
                    Address1 </label><br />
                @Html.TextBoxFor(model => model.Address1, new { @class = 
 "form-control mand", @onkeypress = "return OnlyAlphaNumeric(this);", 
 @onkeyup = "return CPOnlyAlphaNumeric(this);" }).DisableIf(() => 
  Model.IsReadOnly == true)
            </div>
             <div class="col-md-4">
                <label for="" class="control-label">
                   Address2 </label><br />
                @Html.TextBoxFor(model => model.Address2, new { @class = 
 "form-control", @onkeypress = "return OnlyAlphaNumeric(this);", @onkeyup = 
 "return CPOnlyAlphaNumeric(this);" }).DisableIf(() => Model.IsReadOnly == 
  true)
            </div>
             <div class="col-md-4">
                <label for="" class="control-label">
                    Address3 </label><br />
                @Html.TextBoxFor(model => model.Address3, new { @class = 
 "form-control", @onkeypress = "return OnlyAlphaNumeric(this);", @onkeyup = 
 "return CPOnlyAlphaNumeric(this);" }).DisableIf(() => Model.IsReadOnly == 
  true)
            </div>
             <div class="col-md-4">
                <label for="" class="control-label">
                    Address4 </label><br />
                @Html.TextBoxFor(model => model.Address4, new { @class = 
 "form-control", @onkeypress = "return OnlyAlphaNumeric(this);", @onkeyup = 
 "return CPOnlyAlphaNumeric(this);" }).DisableIf(() => Model.IsReadOnly == 
 true)
            </div>
        </div>





        }       
   </div>
 </div>

<script type="text/javascript">

   // Start of  Hide Reset button in edit mode 


       var model = @Html.Raw(Json.Encode(Model))

     $(document).ready(function () {


  function getDocumentDetails()
   {

       alert("2");
   }

     });

  </script>  

1 个答案:

答案 0 :(得分:1)

我同意您在问题中发布的上述评论。对不起Md Aslam,但哪个优势有使用这样的“助手”?

您生成一些代码,这些代码不好阅读,扩展,修改和验证。顺便说一句,我看到你创建了不需要的class="scroll"<table>,这已经过了5年就已经过时了。

您创建了像<{1}}这样的全局函数,这些函数将分配给EditingValidation对象,并且可能与其他JavaScript代码冲突。在页面上使用带有两个网格的“帮助器”将覆盖以前的功能,如window

代码在帮助程序中使用非常具体的选项,如EditingValidationrowNum: 20。因此,我没有看到人们可以真正共享代码。

您使用来自height: 280的{​​{1}}。在这种方式中,您可以非常轻松地产生错误,例如name的值,其中包含空格等特殊字符,或者您可以将更多列作为具有相同column.Index值的列。使用您的代码的人只会考虑他的抽象列模型,并且很容易忘记(或根本不知道)现有的限制。

我会严格建议您指定更清楚的目标,并从开始到结束重写代码。我建议你编写更多纯JavaScript代码,这些代码可以很容易阅读,经过验证(例如在JSHint中)并且易于调试。您可以使用jqQuery事件和列模板来共享您使用的公共代码,并使每个特定网格的使用变得非常容易。