MVC3 On Razor使用(3):封装一个FlexiGrid控件

用户控件,封装一个FlexiGrid的控件,效果图如下:

clip_image002

实现部分:创建一个用户控件View为FlexGridCtl.cshtml,目录结构如下:

image

FlexGridCtl代码如下:

@model CommonLib.SL.IFlexGridModel
@{
    var count = 0;    
}
<script src="@Url.Content("~/Content/flexgrid/flexigrid.pack.js")" type="text/javascript"></script>
<link href="@Url.Content("~/Content/flexgrid/css/flexigrid/flexigrid.css")" rel="stylesheet"  type="text/css" />

<script type="text/javascript">

function test(){}

$(function(){
         $("#@Model.RenderElement").flexigrid
	   (
		  {
			url: '@Model.Action',
			dataType: 'json',
			colModel : [
                     @foreach (var item in Model.FlexGridAttr)
                     {
                        <text>
                        {display:'@(item.Value.DisplayName == null ? item.Key : item.Value.DisplayName)',
                         name:'@item.Key', 
                         '@(item.Value.Width <= 0 ? "50" : item.Value.Width.ToString())', 
                         sortable:@item.Value.Sortable.ToString().ToLower(), 
                         align:'@(item.Value.Align == null ? "left" : item.Value.Align)'}
                        @if (count + 1 != Model.FlexGridAttr.Count)
                         {
                           <text>,</text>
                         }
                        </text>   
                  count++;
               }
	        ],
		  buttons : [
				{name: '新?增?', bclass: 'add', onpress : test},
				{name: '删¦?除y', bclass: 'delete', onpress : test},
				{separator: true}
				],
            @{if (0 < Model.FlexGridAttr.Where(p => p.Value.IsSearch == true).Count())
              {
                  Write(" searchitems : [");

                  foreach (var item in Model.FlexGridAttr)
                  {
                      if (item.Value.IsSearch)
                      {
              <text>
				{display: '@(item.Value.DisplayName == null ? item.Key : item.Value.DisplayName)', name : '@item.Key'},

              </text>
                      }
                  }

                  Write("	],");
              }
            }
			sortname: "@Model.FlexGridAttr.Keys.First()",
			sortorder: "asc",
			usepager: true,
			title: '@Model.Title',
			useRp: true,
			rp: 15,
			showTableToggleBtn: true,
			 700,
			height: 200
			}
			);   
});
</script>

 

注:这里接收实现CommonLib.SL.IFlexGridModel的实现参数,通过循环嵌套动态生成FlexiGrid的代码部分;

该控件页面最终输出一段FlexiGrid的初始js代码并在调用页加载时执行。 

这行代码:url: '@Model.Action',指出了加载文档时去异步调用的url,通过该url返回json数据填充FlexiGrid。

再来看下调用页部分:

Index

上述代码就是View页的代码,只需要调用@Html.Partial(“Controls/FlexGridCtl”,…)这一句则可动态输出FlexiGrid的整个js代码;

其中FlexGridModel<Person>对象则是传递我们定义的参数:

Action:FlexiGrid异步调用的Action的Url ,这个是需要我们在Controller实现的部分

RenderElement:则是FlexiGrid呈现数据的元素Id

Title:FlexiGrid表格的标题

这里我为了方便只定义了这3个参数,当然还可以定义一些其他的参数如:要添加的按钮、回传js函数等等。

后台所用到的cs代码:

类库公用部分,主要是通过反射获取显示列的属性及动态绑定数据:

Index

Model部分:

Index

Contrler部分:

Index
原文地址:https://www.cnblogs.com/sl21100/p/1879937.html